【发布时间】: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)
}
【问题讨论】:
-
是的,这个问题是针对类似的更复杂的(涉及重新打包数据)。我希望有一种方法可以“交叉解释”在运行时完全相同,但具有不同的类型别名。但我猜不是。
标签: go