Reputation: 5182
I have a type myByte byte
that I use because I want to logically differentiate different kinds of bytes.
I can convert easily with byte(myByte(1))
,
but I can't find away to cast or convert an slice: []byte([]myByte{1})
fails.
Is such a thing possible? The bits are the same in memory (right?) so there should be some way, short of copying byte by byte into a new object..
For example, none of this works: 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)
}
Upvotes: 1
Views: 594
Reputation: 42486
You cannot convert slices of your own myByte to a slice of byte.
But you can have your own byte-slice type which can be cast to a byte slice:
package main
import "fmt"
type myBytes []byte
func main() {
var bs []byte
bs = []byte(myBytes{1, 2, 3})
fmt.Println(bs)
}
Depending on your problem this might be a nice solution. (You cannot distinguish a byte from myBytes from a byte, but your slice is typesafe.)
Upvotes: 4
Reputation: 5182
Apparently, there is no way, and the solution is just to loop over the whole slice converting each element and copying to a new slice or "push down" the type conversion to the per-element operations.
Type converting slices of interfaces in go
Upvotes: 1