切片上的图案匹配 [英] Pattern matching on slices

查看:54
本文介绍了切片上的图案匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了这样的事情,有效:

I did something like this, which works:

let s = " \"".as_bytes();
let (space, quote) = (s[0], s[1]);

我想做这样的事情

&[space, quote] = " \"".as_bytes();

但这给了我错误

slice pattern syntax is experimental (see issue #23121)

是否可以做类似的事情?

Is it possible to do something similar?

推荐答案

错误告诉您,切片模式语法是实验性的.这意味着语义不明确,或者语法将来可能会更改.结果,您需要每晚编译器版本并明确请求该功能:

As the error tells you, slice pattern syntax is experimental. This means either the semantics are not clear or the syntax might change in the future. As a result, you need a nightly version of the compiler and to explicitly request that feature:

#![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的长​​度可能不正确.要使模式匹配详尽无遗,您需要一个_大小写或一个..大小写.您尝试过的操作会导致另一个错误:

Also note that you can't just write &[space, quote] = whatever anyway because there is a possibility that whatever is not the right length. To make the pattern matching exhaustive, you need a _ case or a case with ... What you tried would give another error:

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() { /* */ }


截至铁锈1.26 您可以 在数组而不是切片上进行模式匹配.如果您将切片转换为数组,则可以对其进行匹配:


As of Rust 1.26 you can pattern match on an array instead of a slice. If you convert the slice to an array, you can then match on it:

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);
}

这篇关于切片上的图案匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆