golang byte 和 string 有时兼容有时不兼容

golang byte and string Sometimes compatible and sometimes incompatible

这是我的 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
}

参数s在函数append中使用时可以看作slice类型。

但是我定义了一个函数 printBytesappend,

当我这样调用时

printBytes("abcdefg"...)

"abcdefg"好像不是一个类型slice

来自append documentation:

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

除了这种特殊情况(以及 copysimilar case),string 在 Go 中不被视为切片类型。

像这样的“内置”函数允许有不严格遵循 Go 中一般类型规则的特殊情况,因为它们的行为实际上是 language specification itself. See Appending to and copying slices.[=18= 的一部分]