我正在尝试理解字符串和字符串切片的概念。
fn say_hello_slice(slice: &str) {
println!("Hey {}", slice);
}
fn say_hello_string(string: &String) {
println!("{:?}", string);
}
fn print_int(int_ref: &i32) {
println!("{:?}", int_ref);
}
fn main() {
let slice: &str = "you";
let s: String = String::from("String");
say_hello_slice(slice);
say_hello_slice(&s);
let number: i32 = 12345;
print_int(&number);
say_hello_string(&s);
}
当我编译和运行这个程序时,会得到以下输出:
Hey you
Hey String
12345
"String"
我了解当在绑定中添加
&
时,它会成为其绑定类型的引用。例如,在上面的程序中,将 &
添加到 number
中就变成了 &i32
。但我不明白当我将
&
添加到 String
中时它如何工作,从而变成了 &str
。