从高级程序员的角度来看 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即可 。

相关经验推荐