当我尝试将 string
转换为 []int
时,编译失败。我发现字符串可以将 转换为 int32(rune)
和 uint8(byte)
。
这是我的测试代码:
s1 := "abcd"
b1 := []byte(s1)
r1 := []rune(s1)
i1 := []int8(s1) //error
最佳答案
简短的回答是因为语言规范不允许。
非常量值的允许转换: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.
较长的答案是:
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.
将 string
转换为 []byte
是“有用的”,因为这是文本的 UTF-8 编码字节序列,这正是 Go 存储字符串的方式内存,这通常是您应该存储/传输的数据,以便通过字节流(例如 io.Writer
)传递 string
,同样,这是您可以从io.Reader
.
将 string
转换为 []rune
也很有用,它会生成文本的字符( rune ),因此您可以轻松地检查/操作字符string
(在现实生活中经常需要)。
将 string
转换为 []int8
并不是很有用,因为字节流对 byte
进行操作(这是一个别名到 uint8
,而不是 int8
)。如果在特定情况下您需要来自 string
的 []int8
,您可以编写自定义转换器(这很可能会将字符串的各个字节转换为 int8
值)。
关于string - 为什么string不能转为uint8和int32以外的其他数据类型数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55845542/