Rust语法探究(二)

七:匹配,模式

Rust中的match表达式非常强大

let day = 5;
match day {  
  0 | 6 => println!("weekend"),
  1 ... 5 => println!("weekday"),
  _ => println!("invalid"),
}

其中|用于匹配多个值,...匹配一个范围 (包含最后一个值,范围经常用在整数和 char 上。),并且_在这里是必须的, 因为match强制进行穷尽性检查 (exhaustiveness checking),必须覆盖所有的可能值。 如果需要得到|或者...匹配到的值,可以使用@绑定变量:

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

使用ref关键字来得到一个引用:

let x = 5;
let mut y = 5;
match x {    
    // the `r` inside the match has the type `&i32`
    ref r => println!("Got a reference to {}", r),
}
match y {
    // the `mr` inside the match has the type `&i32` and is mutable
    ref mut mr => println!("Got a mutable reference to {}", mr),
}

再看一个使用match表达式来解构元组的例子:

let pair = (0, -2);

match pair {
    (0, y) => println!("x is `0` and `y` is `{:?}`", y),
    (x, 0) => println!("`x` is `{:?}` and y is `0`", x),
    _ => println!("It doesn't matter what they are"),
}

match的这种解构同样适用于结构体或者枚举。如果有必要, 还可以使用..来忽略域或者数据:

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

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

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

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."),
}

此外,Rust还引入了if letwhile let进行模式匹配:

let number = Some(7);
let mut optional = Some(0);

// If `let` destructures `number` into `Some(i)`, evaluate the block.
if let Some(i) = number {
    println!("Matched {:?}!", i);
} else {
    println!("Didn't match a number!");
}

// While `let` destructures `optional` into `Some(i)`, evaluate the block.
while let Some(i) = optional {
    if i > 9 {
        println!("Greater than 9, quit!");
        optional = None;
    } else {
        println!("`i` is `{:?}`. Try again.", i);
        optional = Some(i + 1);
    }
}

八:字符串

Rust有两种主要的字符串类型;&strString 。字符串常量是&'static str类型的 。

String通常通过一个字符串片段调用to_string方法转换而来。 String可以通过一个& 强制转换为&str

let greeting = "Hello there.";    // greeting: &'static str

let mut s = "Hello".to_string();    // mut s: String
println!("{}", s);
s.push_str(", world.");
println!("{}", s);

把 String 转换为&str 的代价很小,不过从 &str 转换到String涉及到分配内存。除非必要,没有理由这样做!

字符串是有效UTF-8编码的,它不支持索引,必须遍历字符串来找到字符串的第N个字符。可以选择把字符串看作一个串独立的字节,或者代码点.

拼接字符串:一个String,可以在它后面接上一个&str 。如果你有两个String ,你需要一个 & ,这个功能叫做 Deref  转换。

let    hello  =  "Hello".to_string();
let    world  =  "world!";
let    hello_world  =  hello + world;

let    hello  =  "Hello".to_string();
let    world  =  "world!".to_string();
let    hello_world  = hello + &world;








你可能感兴趣的:(Rust语法探究(二))