Rust 学习笔记 06:引用与借用 (References & Borrowing) 下
Rust 学习笔记 06:引用与借用 (References & Borrowing) 下 “Borrow checkers are the strict librarians of the programming world.” 上一集我们讲了所有权 (Ownership):把东西给别人(Move),自己就没了。这虽然安全,但太麻烦了。 比如我想计算一个字符串长度,难道每次都要把所有权传进去,算完再传回来? 1// 痛苦的写法 2fn calculate_length(s: String) -> (String, usize) { 3 let length = s.len(); 4 (s, length) // 还要把 s 传回去,心累 5} Rust 说:别急,你可以 借 (Borrow) 啊。 1. 引用 (References) 引用允许你使用值但不获取其所有权。在 Rust 中,用 & 符号表示。 1fn main() { 2 let s1 = String::from("hello"); 3 4 // 传引用:&s1 5 let len = calculate_length(&s1); 6 7 // s1 依然有效!因为我们只是借出去了,没送出去。 8 println!("The length of '{}' is {}.", s1, len); 9} 10 11// 接收引用:&String 12fn calculate_length(s: &String) -> usize { 13 s.len() 14} 这叫 借用 (Borrowing)。就像你借了朋友的书,你看完了得还回去(离开作用域),但书还是朋友的。 ...