介紹
本系列錄制的視訊主要放在B站上Rust死靈書學習視訊
Rust相關的源碼資料在:https://github.com/anonymousGiga
筆記内容
引用與别名
- 引用
- 借用(也就是可變引用)
- 引用的生命周期不能超過被引用的内容(原因:Rust中記憶體在擁有它的變量離開作用域後就被自動釋放)
- 可變引用不能存在别名
fn main() {
//1、引用的生命周期不能超過被引用的内容
let a = String::from("This is a!");
let mut b = &a;
{
let c = String::from("This is c!");
b = &c;
println!("reference c: {}", b);
}
//println!("reference c: {}", b);
println!("Hello, world!");
}
//2、可變引用不存在别名:這裡的别名的定義同C++中别名的定義,而不是說的類型别名
//例如c++中,别名:int a = 10; int &b = a; b為a的别名
//原因:
//考慮如下函數:
//fn compute(input: &u32, output: &mut u32) {
// if *input > 10 {
// *output = 1;
// }
// if *input > 5 {
// *output *= 2;
// }
//}
//可能的優化:
fn compute(input: &u32, output: &mut u32) {
let cached_input = *input; // 将*input放入緩存
if cached_input > 10 {
*output = 1; // x > 10 則必然 x > 5,是以直接加倍并立即退出
} else if cached_input > 5 {
*output *= 2;
}
}
//如果存在别名,則會如下:
// // input == output == 0xabad1dea
// // *input == *output == 20
//if *input > 10 { // true (*input == 20)
// *output = 1; // also overwrites *input, because they are the same
//}
//if *input > 5 { // false (*input == 1)
// *output *= 2;
//}
// // *input == *output == 1
//是以,這就是為什麼Rust不允許别名存在的原因