-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
This is the second item in #23297.
What version of Go are you using (go version
)?
go version go1.9.2 linux/amd64
and the compiler used by the Go playground
What did you do?
The string->[]rune conversion does not work for non-constant user defined string type:
type MyString string
[]rune(MyString("白鵬翔")) // legal, example provided by spec
a := MyString("sss")
b := []rune(a) // compile error: cannot use a (type MyString) as type string in argument to runtime.stringtoslicerune
See https://play.golang.org/p/gunMmHAxytT. There seems no such problem with constant, []byte, or the other converting direction.
What did you expect to see?
I think this should compile. From https://golang.org/ref/spec#Conversions, Version of June 28, 2017:
A non-constant value x can be converted to type T in any of these cases:
...
- x is an integer or a slice of bytes or runes and T is a string type.
- x is a string and T is a slice of bytes or runes.
Based on the following examples provided in the spec, it seems the phrases "string", "slice of bytes", "slice of runes" include defined types as well as the plane "string", "[]byte", "[]rune" types:
// Examples provided in the same section of the spec:
type MyString string
MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
type MyBytes []byte
string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
type MyRunes []rune
string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
[]rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
What did you see instead?
Compile error:
cannot use a (type MyString) as type string in argument to runtime.stringtoslicerune