Hey Everyone, 大家好,
Today is references and borrowing. Immutable references allow reading data without ownership transfer, while mutable references enable modification, subject to rules ensuring exclusive access and preventing data races.
今天的内容是引用和借用。这是内存安全的基本概念。不可变引用允许阅读数据而不需要所有权转移,而可变引用允许修改,但要遵守确保独占访问和防止数据竞争的规则。
Referencing 引用
Yesterday we saw how passing an argument to a function does the same effect as assigning the value to another variable and effectively resulting in a loss of ownership. Well there’s a workaround to that.
昨天我们看到了如何将参数传递给一个函数与将值分配给另一个变量产生相同的效果,并有效地导致所有权的丧失。有一个解决办法。
If you know anything about C, pointers
are an essential concept of C. Well references are similar.
如果你对C有所了解,那么 pointers
是C的一个基本概念。参考文献是相似的。
Lets take a look at the code and understand it:
让我们看看代码并理解它:
fn main(){
let s1: String = String::from("Hello World");
let length: usize = calculate_length(&s1); // & is used to pass in a reference to a string
println!("The length of `{}` is {}" ,s1,length);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
Rust references are pointers t