实施是
// String returns the accumulated string.
func (b *Builder) String() string {
return *(*string)(unsafe.Pointer(&b.buf))
}
Run Code Online (Sandbox Code Playgroud)
根据我的测试,将 []byte 转换为字符串使用“写时复制”,或者编译器生成深复制指令,如果其中任何一个正在更改内部切片:
{
a := []byte{'a'}
s1 := string(a)
a[0] = 'b'
fmt.Println(s1) // a
}
{
a := "a"
b := []byte(a)
b[0] = 'b'
fmt.Println(a) // a
}
Run Code Online (Sandbox Code Playgroud)
那么如果按照下面的方式实现会发生什么?
// String returns the accumulated string.
func (b *Builder) String() string {
return string(b.buf)
}
Run Code Online (Sandbox Code Playgroud) 我正在学习 Rust,以下代码来自在线书籍 The Rust Programming Language链接:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error!
println!("the first word is: {}", word);
}
Run Code Online (Sandbox Code Playgroud)
编译器如下:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' …Run Code Online (Sandbox Code Playgroud)