arrays - string 与 []byte 类型定义

标签 arrays string go types

如果我有这段代码,它会按预期工作:

package main
import "strconv"

type text []byte

func main() {
   hello := text("hello")
   _ = strconv.AppendQuote(hello, " world")
}

但是这段代码失败了:

package main
import "strconv"

type text string

func main() {
   hello := text("hello")
   // cannot use hello (type text) as type string in argument to strconv.Quote
   _ = strconv.Quote(hello)
}

为什么一个通过而另一个失败?我查了文档[1],但没有看到 任何可以解释差异的东西。

  1. https://go.dev/ref/spec#Type_definitions

最佳答案

您要查找的内容位于可分配性下:

https://go.dev/ref/spec#Assignability

特别是:

x's type V and T have identical underlying types and at least one of V or T is not a defined type.

在这两种情况下,基础类型是相同的(在情况 1 中需要 []byte 且传递 text,需要 string并且 text 在情况 2) 中传递,但是 []byte 不是定义的类型,而 string 是,所以它适用于第一种情况,但不是第二个。

关于arrays - string 与 []byte 类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70655543/

相关文章:

json - Go:如何将响应体变成请求体?

Go 交互式外壳

arrays - 连接 postgresql json 数组中对象的字符串值

PHP 检查数组中的条目是否有重复项

python - 在 python 中反转字符串的最快方法

string - 使用文件的内容对其进行重命名

go - Yaml 文件在 Golang 中进行结构解析(翻译)

java - 将图像从 android 串行发送到 java 应用程序时出错 -javax.imageio.IIOException : Bogus Huffman table definition

C动态数组中间插入

javascript - 使用字符串访问 json