Rust Patterns

if let

if let allows you to combine if and let together to reduce the overhead of certain kinds of pattern matches.数据结构

let option = Some(12);
if let Some(x) = option {
    foo(x);
} else {
    bar();
}

while let

In a similar fashion, while let can be used when you want to conditionally loop as long as a value matches a certain pattern.oop

let mut v = vec![1, 3, 5, 7, 11];
while let Some(x) = v.pop() {
    println!("{}", x);
}

复合模式

使用|来匹配复合模式:code

let x = 1;

match x {
    1 | 2 => println!("one or two"),
    3 => println!("three"),
    _ => println!("anything"),
}
//打印结果: one or two

解构

若是有一个复杂的数据类型,例如: struct,咱们能够使用pattern来解构:three

struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

match origin {
    Point { x, y } => println!("({},{})", x, y),
}

咱们使用:来指定不一样的名字:ip

struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

match origin {
    Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
}

若是咱们只关系其中的某些值,咱们没必要指定全部的名字:element

struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

match origin {
    Point { x, .. } => println!("x is {}", x),
}

打印出 x is 0get

解构也彻底适用于tupleenumsstring

忽略绑定

match some_value {
    Ok(value) => println!("got a value: {}", value),
    Err(_) => println!("an error occurred"),
}

fn coordinate() -> (i32, i32, i32) {
    // generate and return some sort of triple tuple
}

let (x, _, z) = coordinate();

类似的,咱们能够使用..来忽略多个值:it

enum OptionalTuple {
    Value(i32, i32, i32),
    Missing,
}

let x = OptionalTuple::Value(5, -2, 3);

match x {
    OptionalTuple::Value(..) => println!("Got a tuple!"),
    OptionalTuple::Missing => println!("No such luck."),
}

ref 和ref mut

若是须要获取一个引用,咱们能够使用ref关键字:io

let x = 5;

match x {
    ref r => println!("Got a reference to {}", r),
}

这里,rmatch中的数据类型为&i32,换句话说,ref在使用patterns中建立了一个引用。若是须要一个可变引用,能够使用ref mut

let mut x = 5;

match x {
    ref mut mr => println!("Got a mutable reference to {}", mr),
}

Ranges

咱们使用...来匹配一个范围的值:

let x = 1;

match x {
    1 ... 5 => println!("one through five"),
    _ => println!("anything"),
}

绑定

咱们能够经过@绑定值到一个命名变量上:

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}

在匹配复杂的数据结构中是很是有用的,例如:

#[derive(Debug)]
struct Person {
    name: Option<String>,
}

let name = "Steve".to_string();
let mut x: Option<Person> = Some(Person { name: Some(name) });
match x {
    Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
    _ => {}
}

使用@|,能够分别匹配不一样的部分:

let x = 5;

match x {
    e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
    _ => println!("anything"),
}

关卡

enum OptionalInt {
    Value(i32),
    Missing,
}

let x = OptionalInt::Value(5);

match x {
    OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
    OptionalInt::Value(..) => println!("Got an int!"),
    OptionalInt::Missing => println!("No such luck."),
}
相关文章
相关标签/搜索