我有一個type myByte byte
我使用,因爲我想在邏輯上區分不同種類的字節。在Go中,如何將[] myByte轉換爲[]字節?
我可以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)
}
看起來像這是相關的:http://stackoverflow.com/questions/4308385/converting-several-bytes-in-數組到另一種類型的進入 – BraveNewCurrency
是的,這個問題是一個類似的更復雜(涉及重新包裝數據)。我希望能夠有一種「交叉解釋」的方式,它們在運行時完全相同,但是具有不同的類型別名。但我猜不。 – misterbee