为什么字符串不能转换为除uint8和int32之外的其他数据类型数组?

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 type T in any of these cases:

  • x is assignable to T.
  • ignoring struct tags (see below), x's type and T have identical underlying types.
  • ignoring struct tags (see below), x's type and T are pointer types that are not defined types, and their pointer base types have identical underlying types.
  • x's type and T are both integer or floating point types.
  • x's type and T are both complex types.
  • 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.

The longer answer is:

Spec: Conversions: Conversions to and from a string type:

  1. 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".

  2. Converting a slice of bytes to a string type yields a string whose successive bytes are the elements of the slice.

  3. Converting a slice of runes to a string type yields a string that is the concatenation of the individual rune values converted to strings.

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

  5. 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 bytes (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).

from the go documentation:

string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.

so a string is the same as []uint8

that is why you can convert it to rune and uint8