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枚舉
Rust枚舉
enum關鍵字允許創建標籤聯合, 它可以被用作代數數據類型 (ADT)。
// Allow Cons and Nil to be referred to without namespacing
use List::{Cons, Nil};
// A linked list node, which can take on any of these two variants
enum List {
// Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(u32, Box
),
// Nil: A node that signifies the end of the linked list
Nil,
}
// Methods can be attached to an enum
impl List {
// Create an empty list
fn new() -> List {
// `Nil` has type `List`
Nil
}
// Consume a list, and return the same list with a new element at its front
fn prepend(self, elem: u32) -> List {
// \`Cons\` also has type List
Cons(elem, Box::new(self))
}
// Return the length of the list
fn len(&self) -> u32 {
// \`self\` has to be matched, because the behavior of this method
// depends on the variant of \`self\`
// \`self\` has type \`&List\`, and \`\*self\` has type \`List\`, matching on a
// concrete type \`T\` is preferred over a match on a reference \`&T\`
match \*self {
// Can't take ownership of the tail, because \`self\` is borrowed;
// instead take a reference to the tail
Cons(\_, ref tail) => 1 + tail.len(),
// Base Case: An empty list has zero length
Nil => 0
}
}
// Return representation of the list as a (heap allocated) string
fn stringify(&self) -> String {
match \*self {
Cons(head, ref tail) => {
// \`format!\` is similar to \`print!\`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
// Create an empty linked list
let mut list = List::new();
// Append some elements
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Show the final state of the list
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}