When I try to convert string
to []int
, compile fail. and I found string can convert to int32(rune)
and uint8(byte)
.
This is my test code:
s1 := "abcd"
b1 := []byte(s1)
r1 := []rune(s1)
i1 := []int8(s1) //error
When I try to convert string
to []int
, compile fail. and I found string can convert to int32(rune)
and uint8(byte)
.
This is my test code:
s1 := "abcd"
b1 := []byte(s1)
r1 := []rune(s1)
i1 := []int8(s1) //error
The short answer is because the language specification does not allow it.
The allowed conversions for non-constant values: Spec: Conversions:
A non-constant value
x
can be converted to typeT
in any of these cases:
x
is assignable toT
.- ignoring struct tags (see below),
x
's type andT
have identical underlying types.- ignoring struct tags (see below),
x
's type andT
are pointer types that are not defined types, and their pointer base types have identical underlying types.x
's type andT
are both integer or floating point types.x
's type andT
are both complex types.x
is an integer or a slice of bytes or runes andT
is a string type.x
is a string andT
is a slice of bytes or runes.
The longer answer is:
Spec: Conversions: Conversions to and from a string type:
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to
"\uFFFD"
.Converting a slice of bytes to a string type yields a string whose successive bytes are the elements of the slice.
Converting a slice of runes to a string type yields a string that is the concatenation of the individual rune values converted to strings.
Converting a value of a string type to a slice of bytes type yields a slice whose successive elements are the bytes of the string.
Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string.
Converting a string
to []byte
is "useful" because that is the UTF-8 encoded byte sequence of the text, this is exactly how Go stores strings in memory, and this is usually the data you should store / transmit in order to deliver a string
over byte-streams (such as io.Writer
), and similarly, this is what you can get out of an io.Reader
.
Converting a string
to []rune
is also useful, it result in the characters (runes) of the text, so you can easily inspect / operate on the characters of a string
(which is often needed in real-life applications).
Converting a string
to []int8
is not so much useful given that byte-streams operate on byte
s (which is an alias to uint8
, not int8
). If in a specific case you need a []int8
from a string
, you can write your custom converter (which would most likely convert the individual bytes of the string to int8
values).