1.42 之后 Rust 拥有了和 Haskell Programming Language 差不多的对 slice 做 pattern match 的能力,要注意的是这里的 match 只能针对的是 slice,如果对象是 Vec 之类的,需要通过切片语法 lst[..] 先转换为 slice 再进行匹配。具体的用法我们参照下面这个例子。

fn print_words(sentence: &str) {
	let words: Vec<_> = sentence.split_whitespace().collect();
 
	match words.as_slice() {
		[] | [_] => println!("Ingore one word or no word"),
		[word, name] => println!("Found 2 word: {}, {}", word, name),
		["hello", name, ..] => println!("capture second word name: {}", name),
		["hello" | "hi", name, rest @ ..] => println!("test with | operator, and collect rust, {}, {:?}", name, rest),
		[first, middle @ ..., last] if first == last => println!("capture middles {}", middle),
		_ => println!("Found {} words: {:?}", words.len(), words),
	}
}

另外 RustPattern Match 不止是在 match 中使用,在 let 和函数参数中同样可以使用。

fn format_coordinates([x, y]: [f32; 2]) -> String {
	format!("{}|{}", x, y)
}
 
fn main() {
	let point = [3.14, -42.0];
 
	println!("{}", format_coordinates(point));
 
	let [x, y] = point;
	println!("x: {}, y: {}", x, y);
	// Much more ergonomic than writing this!
	// let x = point[0];
	// let y = point[1];
}

更多例子可以查看这篇 Daily Rust: Slice Patterns 博客。