正如错误告诉您的那样,切片模式语法是实验性的。这意味着要么语义不明确,要么语法可能在未来发生变化。因此,您需要一个夜间版本的编译器并明确请求该功能:
#![feature(slice_patterns)]
fn main() {
match " \"".as_bytes() {
&[space, quote] => println!("space: {:?}, quote: {:?}", space, quote),
_ => println!("the slice lenght is not 2!"),
}
}
还请注意,无论如何您都不能只写&[space, quote] = whatever,因为whatever 的长度可能不合适。要使模式匹配详尽无遗,您需要一个 _ 案例或 .. 案例。你尝试过的会出现另一个错误:
error[E0005]: refutable pattern in local binding: `&[]`, `&[_]` and `&[_, _, _, ..]` not covered
--> src/main.rs:4:9
|
4 | let &[space, quote] = " \"".as_bytes();
| ^^^^^^^^^^^^^^^ patterns `&[]`, `&[_]` and `&[_, _, _, ..]` not covered
|
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
= note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html
help: you might want to use `if let` to ignore the variant that isn't matched
|
4 | if let &[space, quote] = " \"".as_bytes() { /* */ }
从Rust 1.26 开始,您可以在数组而不是切片上进行模式匹配。如果你convert the slice to an array,那么你就可以匹配了:
use std::convert::TryInto;
fn main() {
let bytes = " \"".as_bytes();
let bytes: &[_; 2] = bytes.try_into().expect("Must have exactly two bytes");
let &[space, quote] = bytes;
println!("space: {:?}, quote: {:?}", space, quote);
}