让我们转换string为[]byte:
func toBytes(s string) []byte {
return []byte(s) // What happens here?
}
Run Code Online (Sandbox Code Playgroud)
这个演员阵营有多贵?正在进行复制吗?就我在Go规范中看到的那样:字符串的行为类似于字节切片但是不可变,这至少应该涉及复制以确保后续切片操作不会修改我们的字符串s.反向对话会发生什么?[]byte <-> string会话是否涉及编码/解码,如utf8 < - >符文?
如果不可变类对象副本将等于原始副本那么为什么StringJava 中的类具有复制构造函数?这是一个错误还是这个实施背后的原因?在Java文档中,它被指定为:
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
public String(String original) {
....
....}
Run Code Online (Sandbox Code Playgroud) 我正在尝试string使用utf8库有效地计算 utf-8中的符文。此示例是否最佳,因为它不复制基础数据?
https://golang.org/pkg/unicode/utf8/#example_DecodeRuneInString
func main() {
str := "Hello, ??" // let's assume a runtime-provided string
for len(str) > 0 {
r, size := utf8.DecodeRuneInString(str)
fmt.Printf("%c %v\n", r, size)
str = str[size:] // performs copy?
}
}
Run Code Online (Sandbox Code Playgroud)
我在(不安全的)反射库中找到了StringHeader。这是stringGo中 a 的确切结构吗?如果是这样,可以想象,对字符串进行切片只是更新Data或分配一个新的字符串StringHeader。
type StringHeader struct {
Data uintptr
Len int
}
Run Code Online (Sandbox Code Playgroud)
奖励:在哪里可以找到执行string切片的代码,以便我可以自己查找?有这些吗?
https://golang.org/src/runtime/slice.go
https://golang.org/src/runtime/string.go
该相关SO答案,从转化时表明运行时字符串招致拷贝string到[]byte。