string - 为什么string不能转为uint8和int32以外的其他数据类型数组?

标签 string go type-conversion slice

当我尝试将 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 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.

较长的答案是:

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.

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/

相关文章:

java - 从字节数组创建字符串时消除默认零

go - 如何在不进入 Golang 循环的情况下捕获按键

floating-point - 无法将 IEEEReal.rounding_mode 与 real 统一

javascript - 如何在 JavaScript 中转换字符串日期

string - Groovy 中使用 "body"进行高效字符串替换策略

python - 删除换行符时遇到问题

string - Matlab整数字符串解码...速度优化

go - 如何在原始类型的 Go 中使用 `google.protobuf.Any`?

go - 我如何使用 Redigo "SCRIPT FLUSH"?

C 语言 - [原地复制] float* 到 char* 和反向