欧美日韩国产一区二区|qovd片|小明个人发布看看|小浪货你夹真紧水又多|老头把我添高潮了A片故|99热久久精品国产一区二区|久久久春色AV

從高級程序員的角度來看 rust編程入門實戰與進階( 四 )


結構可以通過如下幾種方式定義 。
● 使用Tuple作為聲明(類似于元組的別名)
struct Something(u8, u16); // a struct with 2 numbers, one unsigned 8 bit, the other one unsigned 16 bit
● 使用對象表示法(類似于聲明類或對象)
struct Something { value: u8, another_value: u16}
● 使用struct作為別名
struct Something = u8; // a single value
這種方法的適用情況為:你試圖創建一個enum,而其值可能是正在定義的結構,而該結構中又要(直接或間接)引用該enum 。
struct MaybeRecursive { possibly_self: Option<MaybeRecursive> // error!}struct MaybeRecursive { possibly_self: Option<Box<MaybeRecursive>> // fine}
我在為自己的shell創建抽象語法樹時 , 就遇到了這個問題 。
要創建結構的實例,需要使用下述寫法(類似于C#中定義數組):
Something { variable: 1, another_variable: 1234}

從高級程序員的角度來看 rust編程入門實戰與進階

文章插圖
定義enum
下面是示例:
enum EnumName { First, Second}
可以為enum指定數值(例如序列化或反序列化數值的情況):
enum EnumName { First = 1, Second // auto incremented}
更強大的寫法如下:
enum EnumName { WithValue(u8), WithMultipleValues(u8, u64, SomeStruct), CanBeSelf(EnumName), Empty}
你可以用match提取出值 。
從高級程序員的角度來看 rust編程入門實戰與進階

文章插圖
Match
match是Rust最強大的功能之一 。
Match是更強大的switch語句 。使用方法與普通的swtich語句一樣,除了一點:它必須覆蓋所有可能的情況 。
let var = 1;match var { 1 => println!("it's 1"), 2 => println!("it's 2"), // following required if the list is not exhaustive _ => println!("it's not 1 or 2")}
也可以match范圍:
match var { 1..=2 => println("it's between 1 and 2 (both inclusive)"), _ => println!("it's something else")}
也可以什么都不做:
match var { _ => {}}
可以使用match安全地unwrap Result<T, E>和Option<T>,以及從其他enum中獲取值:
let option: Option<u8> = Some(1);match option { Some(i) => println!("It contains {i}"), None => println!("it's empty :c") // notice we don't need _ here, as Some and None are the only possible values of option, thus making this list exhaustive}
如果你不使用i(或其他值),Rust會發出警告 。你可以使用_來代替 。
match option { Some(_) => println!("yes"), None => println!("no")}
match也是表達式:
let option: Option<u8> = Some(1);let surely = match option { Some(i) => i, None => 0}println!("{surely}");
你可以看看Option的文檔(或通過IDE的自動補齊 , 看看都有哪些可以使用的trait或方法) 。
你也許注意到了,你可以使用.unwrap_or(val)來代替上述代碼(上述match等價于.unwrap_or(0)) 。
從高級程序員的角度來看 rust編程入門實戰與進階

文章插圖
Loop
loop循環是最簡單的循環 。只需要使用loop即可 。

相關經驗推薦