我试图理解字符串和字符串切片的概念.
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);
}
Run Code Online (Sandbox Code Playgroud)
编译运行时,该程序给出以下输出:
Hey you
Hey String
12345
"String"
Run Code Online (Sandbox Code Playgroud)
据我所知,当&添加到绑定时,它将成为对其绑定类型的引用.例如,&以number在上面的程序中变&i32.
我不明白它是如何工作当我添加&到String它变成&str.