Rust教學
Rust下載和安裝
Rust簡介
Rust Hello World
Rust的特點
Rust註釋
Rust開發環境安裝
Rust文檔
Rust第一個程序
Rust格式化打印
Rust調試
Rust顯示
測試用例:列表
Rust格式化
Rust原語
Rust常量和運算符
Rust元組
Rust數組和切片
Rust自定義類型
Rust結構
Rust可視性
Rust枚舉
Rust常量
Rust變量綁定
Rust變量綁定-可變性
Rust變量綁定-範圍和陰影
Rust變量綁定-聲明
Rust類型轉換
Rust類型轉換 - 字面量
Rust類型轉換-推導
Rust類型轉換 - 別名
Rust表達式
Rust if/else語句
Rust循環
Rust嵌套和標籤
Rust while循環
Rust for和範圍
Rust匹配/match
Rust匹配析構元組
Rust解構枚舉
Rust指針和引用
Rust解構結構
Rust Guards
Rust綁定
Rust if let
Rust while let
Rust函數
Rust方法
Rust閉包
Rust捕捉
Rust作爲輸入參數
Rust匿名類型
Rust輸入函數
Rust作爲輸出參數
Rust指針和引用
指針和引用
對於指針,一個區別是需要在析構之時會解除引用 ,因爲它們使用不同的概念,如C語言。
- 解除引用使用
*
- 構析使用
&
,ref
, 和ref mut
fn main() {
// Assign a reference of type `i32`. The `&` signifies there
// is a reference being assigned.
let reference = &4;
match reference {
// If \`reference\`s is pattern matched against \`&val\`, it results
// in a comparison like:
// \`&i32\`
// \`&val\`
// ^ We see that if the matching \`&\`s are dropped, then the \`i32\`
// should be assigned to \`val\`.
&val => println!("Got a value via destructuring: {:?}", val),
}
// To avoid the \`&\`, you dereference before matching.
match \*reference {
val => println!("Got a value via dereferencing: {:?}", val),
}
// What if you don't start with a reference? \`reference\` was a \`&\`
// because the right side was already a reference. This is not
// a reference because the right side is not one.
let \_not\_a\_reference = 3;
// Rust provides \`ref\` for exacty this purpose. It modifies the
// assignment so that a reference is created for the element; this
// reference is assigned.
let ref \_is\_a\_reference = 3;
// Accordingly, by defining 2 values without references, references
// can be retrieved via \`ref\` and \`ref mut\`.
let value = 5;
let mut mut\_value = 6;
// Use \`ref\` keyword to create a reference.
match value {
ref r => println!("Got a reference to a value: {:?}", r),
}
// Use \`ref mut\` similarly.
match mut\_value {
ref mut m => {
// Got a reference. Gotta dereference it before we can
// add anything to it.
\*m += 10;
println!("We added 10. \`mut\_value\`: {:?}", m);
},
}
}