猿问

戈朗字节和字符串 有时兼容,有时不兼容

这是我的戈朗代码



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

}

在函数 中使用该参数时,可以将其视为类型。ssliceappend


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


当我像这样调用时


printBytes("abcdefg"...)

似乎不被视为一种类型"abcdefg"slice


慕婉清6462132
浏览 66回答 1
1回答

慕侠2389804

从文档中:append作为一种特殊情况,将字符串附加到字节切片是合法的,如下所示:slice = append([]byte("hello "), "world"...)除了此特殊情况(以及类似的情况),在 Go 中不被视为切片类型。copystring像这样的“内置”函数允许具有不严格遵循Go中一般类型规则的特殊情况,因为它们的行为实际上是语言规范本身的一部分。请参阅追加和复制切片。
随时随地看视频慕课网APP

相关分类

Java
我要回答