英文:
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) // 通过
bytes = append(bytes, []byte{1, 2, 3}...) // 通过
bytes = append(bytes, "hello"...) // 也通过,参考:作为特例,将字符串附加到字节切片是合法的
}
func TestTwo(t *testing.T) {
printBytes([]byte{1, 2, 3}...) // 通过
printBytes("abcdefg"...) // 失败
}
func printBytes(b ...byte) {
fmt.Println(b)
}
这些是 <code>strings.Builder</code>
中的一些代码:
func (b *Builder) WriteString(s string) (int, error) {
b.copyCheck()
b.buf = append(b.buf, s...)
return len(s), nil
}
参数 <code>s</code>
在使用函数 <code>append</code>
时可以被视为 <code>slice</code>
类型。
但是我定义了一个类似于 <code>append</code>
的函数 <code>printBytes</code>
,
当我这样调用时:
printBytes("abcdefg"...)
<code>"abcdefg"</code>
似乎不被视为 <code>slice</code>
类型。
英文:
This is my golang code
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)
}
These are some code in <code>strings.Builder</code>
func (b *Builder) WriteString(s string) (int, error) {
b.copyCheck()
b.buf = append(b.buf, s...)
return len(s), nil
}
The param <code>s</code> can be regards as <code>slice</code> type when be used in function <code>append</code> .
But I defined a function <code>printBytes</code> like <code>append</code>,
when I invoke like this
printBytes("abcdefg"...)
The <code>"abcdefg"</code> seems like not be regards as a type <code>slice</code>
答案1
得分: 7
从append
文档中可以看到:
> 作为一个特例,将字符串追加到字节切片是合法的,像这样:
> > slice = append([]byte("hello "), "world"...)
。
除了这个特例(以及copy
的类似情况),在Go中,string
不像切片类型一样对待。
像这样的“内置”函数允许有一些特殊情况,它们不严格遵循Go的一般类型规则,因为它们的行为实际上是语言规范的一部分。请参阅追加和复制切片。
英文:
From the append
documentation:
> As a special case, it is legal to append a string to a byte slice, like this:
> > slice = append([]byte("hello "), "world"...)
Other than this special case (and a similar case for copy
), string
is not treated like a slice type in Go.
"Built-in" functions like this are allowed to have special cases that don't strictly follow the general type rules in Go, because their behaviour is actually part of the language specification itself. See Appending to and copying slices.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论