【问题标题】:In Go, how do I convert []myByte to []byte?在 Go 中,如何将 []myByte 转换为 []byte?
【发布时间】:2013-07-25 14:49:09
【问题描述】:

我有一个type myByte byte,因为我想在逻辑上区分不同类型的字节。

我可以使用byte(myByte(1)) 轻松转换,

但我无法转换或转换切片:[]byte([]myByte{1}) 失败。

这样的事情可能吗?这些位在内存中是相同的(对吗?)所以应该有一些方法,没有一个字节一个字节地复制到一个新对象中..

例如,这些都不起作用:http://play.golang.org/p/WPhD3KufR8

package main

type myByte byte

func main() {
a := []myByte{1}

fmt.Print(byte(myByte(1))) // Works OK

fmt.Print([]byte([]myByte{1})) // Fails: cannot convert []myByte literal (type []myByte) to type []byte

// cannot use a (type []myByte) as type []byte in function argument
// fmt.Print(bytes.Equal(a, b))

// cannot convert a (type []myByte) to type []byte
// []byte(a)

// panic: interface conversion: interface is []main.myByte, not []uint8
// abyte := (interface{}(a)).([]byte)
}

【问题讨论】:

  • 看起来这是相关的:stackoverflow.com/questions/4308385/…
  • 是的,这个问题是针对类似的更复杂的(涉及重新打包数据)。我希望有一种方法可以“交叉解释”在运行时完全相同,但具有不同的类型别名。但我猜不是。

标签: go


【解决方案1】:

您不能将自己的 myByte 切片转换为字节切片。

但是您可以拥有自己的字节片类型,该类型可以转换为 一个字节切片:

package main

import "fmt"

type myBytes []byte

func main() {
     var bs []byte
     bs = []byte(myBytes{1, 2, 3})
     fmt.Println(bs)
}

根据您的问题,这可能是一个不错的解决方案。 (您无法将字节与 myBytes 与字节区分开, 但你的切片是类型安全的。)

【讨论】:

  • 当然,但这只是将问题转移到表格的另一边:type myByte byte; myBytes{myByte(1)} 无法编译。如果我实际上不太关心单个 myBytes,那就太好了。 myBytes{byte(myByte(1))} 工作,这看起来很傻,但我可以明智地沿着更长的程序传播。谢谢!
【解决方案2】:

显然,没有办法,解决方案只是循环整个切片转换每个元素并复制到新切片或“下推”类型转换到每个元素的操作。

Type converting slices of interfaces in go

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-14
    • 2012-06-26
    • 2016-10-10
    • 2013-01-27
    • 2014-11-22
    • 1970-01-01
    • 2018-03-25
    • 2021-07-28
    相关资源
    最近更新 更多