fn main() {let s1 = String::from("hello");let len = calculate_length(&s1);println!("The length of '{}' is {}.", s1, len);}fn calculate_length(s: &String) -> usize {s.len()}
这些 & 符号就是 引用,它们允许你使用值但不获取其所有权。
我们将获取引用作为函数参数称为 借用(borrowing)
fn main() {let mut s = String::from("hello");// 可变引用 &mutchange(&mut s);}fn change(some_string: &mut String) {some_string.push_str(", world");}
引用的规则
- 在任意给定时间,要么 只能有一个可变引用,要么 只能有多个不可变引用。
- 引用必须总是有效的。
let mut s = String::from("hello");let r1 = &s;let r2 = &s; // 不可变没问题println!("{} and {}", r1, r2);// 此位置后 r1 r2 已归还引用let r3 = &mut s; // 没问题println!("{}", r3);
let mut s = String::from("hello");let r1 = &s; // 没问题let r2 = &s; // 没问题let r3 = &mut s; // 已有多个不可变引用 不能再有可变引用println!("{}, {}, and {}", r1, r2, r3);
let mut v = vec![1, 2, 3, 4, 5];let third = &v[0];v.push(6);println!("third is {}", third);
