我做了这样的事情,它有效:
let s = " \"".as_bytes();
let (space, quote) = (s[0], s[1]);
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情
&[space, quote] = " \"".as_bytes();
Run Code Online (Sandbox Code Playgroud)
但它给了我错误
let s = " \"".as_bytes();
let (space, quote) = (s[0], s[1]);
Run Code Online (Sandbox Code Playgroud)
有没有可能做类似的事情?
正如错误告诉您的那样,切片模式语法是实验性的。这意味着要么语义不明确,要么语法将来可能会发生变化。因此,您需要一个夜间版本的编译器并明确请求该功能:
#![feature(slice_patterns)]
fn main() {
match " \"".as_bytes() {
&[space, quote] => println!("space: {:?}, quote: {:?}", space, quote),
_ => println!("the slice lenght is not 2!"),
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您不能随便写&[space, quote] = whatever
,因为可能whatever
长度不正确。为了使模式匹配详尽无遗,您需要一个_
案例或一个带有..
. 您尝试过的操作会产生另一个错误:
#![feature(slice_patterns)]
fn main() {
match " \"".as_bytes() {
&[space, quote] => println!("space: {:?}, quote: {:?}", space, quote),
_ => println!("the slice lenght is not 2!"),
}
}
Run Code Online (Sandbox Code Playgroud)
从Rust 1.26 开始,您可以对数组而不是切片进行模式匹配。如果将切片转换为数组,则可以对其进行匹配:
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2722 次 |
最近记录: |