slice conversion query

45 views
Skip to first unread message

kortschak

unread,
Jan 29, 2012, 6:39:48 PM1/29/12
to golang-nuts
Can someone explain why I can't do this:

package main

type letter byte

func main() {
_ = []letter([]byte{})
}

The underlying representation is the same, so I can't see why this
conversion is not allowed, i.e. its not the same situation as
[]byte([]int{}) or []T([]interface{}).

Just to make this clear from the outset, I'm not asking why the
compiler disallows it (the answer being the spec, as far as I can see,
does not specify that it is possible), I'm asking why the spec
disallows it (this seems to be a common confusion in this type of
question).

Rob 'Commander' Pike

unread,
Jan 29, 2012, 7:08:31 PM1/29/12
to kortschak, golang-nuts

Allowing it would complicate the spec and the rules for when conversions are allowed are complicated already. This case (base types match) doesn't come up all that often, so itt doesn't seem worthwhile. Once you decide conversion rules should start digging inside the type, things can get messy fast.

-rob

kortschak

unread,
Jan 29, 2012, 7:14:57 PM1/29/12
to golang-nuts
No worries. Thanks.

John Asmuth

unread,
Jan 29, 2012, 7:20:12 PM1/29/12
to golan...@googlegroups.com
If you know for sure that the underlying data matches perfectly, you can use the unsafe package to go from one to the other.

*(*[]byte)(unsafe.Pointer(&theLetterSlice))
Reply all
Reply to author
Forward
0 new messages