golang字节和字符串有时兼容有时不兼容
这是我的 golang 代码
package test
import (
"fmt"
"testing"
)
func TestOne(t *testing.T) {
bytes := make([]byte, 0)
bytes = append(bytes, 1, 2, 3) // pass
bytes = append(bytes, []byte{1, 2, 3}...) // pass
bytes = append(bytes, "hello"...) // pass too, ok. reference: As a special case, it is legal to append a string to a byte slice
}
func TestTwo(t *testing.T) {
printBytes([]byte{1, 2, 3}...) // pass
printBytes("abcdefg"...) // fail
}
func printBytes(b ...byte) {
fmt.Println(b)
}
这些是一些代码 strings.Builder
func (b *Builder) WriteString(s string) (int, error) {
b.copyCheck()
b.buf = append(b.buf, s...)
return len(s), nil
}
param在 function 中使用时可以s视为slice类型append。
但是我定义的函数printBytes一样append,
当我这样调用时
printBytes("abcdefg"...)
该"abcdefg"好像不能被作为类型slice
回答
从append 文档:
作为一种特殊情况,将字符串附加到字节切片是合法的,如下所示:
slice = append([]byte("hello "), "world"...)
除了这种特殊情况(以及类似情况下的copy),string不视同于围棋的片段类型。
像这样的“内置”函数允许有不严格遵循 Go 中一般类型规则的特殊情况,因为它们的行为实际上是语言规范本身的一部分。请参阅附加到和复制切片。