【问题标题】:Pattern matching on slices切片上的模式匹配
【发布时间】:2016-11-27 11:43:34
【问题描述】:

我做了这样的事情,效果很好:

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

我想做这样的事情

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

但它给了我错误

slice pattern syntax is experimental (see issue #23121)

有没有可能做类似的事情?

【问题讨论】:

  • 如错误中所述,语法是实验性的,因此您最好暂时不要使用它。为什么要使用切片模式?
  • 是不是还没有实现?事实证明,我不再需要这样做了,因为我找到了解决问题的更好方法。但是,我仍然很好奇为什么它不起作用。我可能有一天需要使用它。
  • @x4rkz:实验性意味着尚未决定是否按原样实施、以其他方式实施或根本不实施。它在不断变化。
  • 已实现,但语义随时可能发生变化。为防止意外破坏您的代码,您需要明确告诉编译器选择加入这些不稳定的功能以使用它。
  • 你去看看issue 23121,就像错误信息说的那样?

标签: rust matching


【解决方案1】:

正如错误告诉您的那样,切片模式语法是实验性的。这意味着要么语义不明确,要么语法可能在未来发生变化。因此,您需要一个夜间版本的编译器并明确请求该功能:

#![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);
}

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多