1

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)
}
misterbee
  • 5,142
  • 3
  • 25
  • 34
  • 1
    Looks like this is relevant: http://stackoverflow.com/questions/4308385/converting-several-bytes-in-an-array-to-another-type-in-go – BraveNewCurrency Jul 25 '13 at 04:33
  • Yeah, that question is for a similar more-complicated (involving re-packing data). I was hoping that there would be a way to "cross-interpret" that are exactly the same in the runtime, but have different type aliases. But I guess not. – misterbee Jul 25 '13 at 04:37

2 Answers2

4

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.)

Volker
  • 40,468
  • 7
  • 81
  • 87
  • Sure, but that just moves the problem to the other side of the table: `type myByte byte; myBytes{myByte(1)}` does not compile. It's good if I don't actually care much for individual myBytes. `myBytes{byte(myByte(1))}` works, which looks silly as one line, but may me sensible spread along a longer program. Thanks! – misterbee Jul 25 '13 at 19:02
1

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

Community
  • 1
  • 1
misterbee
  • 5,142
  • 3
  • 25
  • 34