如果我有这段代码,它会按预期工作:
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],但没有看到 任何可以解释差异的东西。
最佳答案
您要查找的内容位于可分配性下:
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/