本文用作方便自我理解而写,如有错,恳请指正,谢谢
引用在rust语言中采用&取地址符表示,它用来创建一个指向值的应用,但是并不拥有它,所以当引用离开其值指向的作用域后也不会被丢弃,下图是这个引用的指向
这是一个使用引用的例子,可以运行看到,这里使用了引用,使得s的所有权并没有转移,因为引用并不会拥有这个值,所以也就无法对这个值进行修改,比如下方第二个代码块就会报错
fn main() {
let s = String::from("hello");
println!("{s}");
let len = length(&s);
println!("{len}");
println!("{s}");
}
fn length(s: &String) -> usize {
return s.len()
}
fn main() {
let mut s = String::from("hello");
println!("{s}");
append(&s);
println!("{s}");
}
fn append(mut s: &String) {
s.push_str("world")
}
而想要修改这个值,我们就会使用到借用&mut
fn main() {
let mut s = String::from("hello");
println!("{s}");
append(&mut s);
println!("{s}");
}
fn append(mut s: &mut String) {
s.push_str("world")
}
但是如果同时出现了引用和借用,引用的变量将无法使用,因为借用可能会改变原本的值,所以根据rust的安全规则释放了该值的内存,在给定时间里,要么只能有一个同一值得可变引用或多个不可变引用
fn main() {
let mut s = String::from("hello");
println!("{s}");
let s1 = &s;
let s2 = &s;
let s3 = &mut s;
println!("{s1}");
}