为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕婉清6462132 2022-09-12 16:25:17
这是我的戈朗代码package testimport (    "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.Builderfunc (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
查看完整描述

1 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

文档中append

作为一种特殊情况,将字符串附加到字节切片是合法的,如下所示:

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

除了此特殊情况(以及类似的情况),在 Go 中不被视为切片类型。copystring

像这样的“内置”函数允许具有不严格遵循Go中一般类型规则的特殊情况,因为它们的行为实际上是语言规范本身的一部分。请参阅追加和复制切片


查看完整回答
反对 回复 2022-09-12
  • 1 回答
  • 0 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号