4

我正在尝试在Strings 的切片上使用切片模式。这不起作用,因为 Rust 不String将切片的 s 与&str文字匹配。我不知道如何将 s 的切片转换为Strings 的切片&str

#![feature(slice_patterns)]

fn main() {
    // A slice of strings.
    let x = ["foo".to_owned(), "bar".to_owned()];
    match x {
        ["foo", y] => println!("y is {}.", y),
        _ => println!("I did not expect this."),
    }
}

操场

4

1 回答 1

2

从技术上讲,您没有Strings ( &[String])的切片,而是有s ( ) 的数组String[String; 2]

让我们看一个较小的案例:

fn main() {
    match "foo".to_owned() {
        "foo" => println!("matched"),
        _ => unreachable!(),
    }
}

在这里,我们得到相同的错误消息:

error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
3 |         "foo" => println!("matched"),
  |         ^^^^^ expected struct `std::string::String`, found reference
  |
  = note: expected type `std::string::String`
             found type `&'static str`

在这种情况下,解决方法是将 更改String为 a &str,这是切片模式所理解的:

let s = "foo".to_owned();
match s.as_str() {
    "foo" => println!("matched"),
    _ => unreachable!(),
}

也可以看看:

那么,我们如何将其扩展到您的示例?直截了当的事情是两次做同样的事情:

fn main() {
    let x = ["foo".to_owned(), "bar".to_owned()];

    match [x[0].as_str(), x[1].as_str()] {
        ["foo", y] => println!("y is {}.", y),
        _ => unreachable!(),
    }
}

但是,这不适用于切片 ( &[T]) 的情况,因为我们只处理两个值,而不是任意数量。在这种情况下,我们需要做一个临时的Vec


fn main() {
    let x = ["foo".to_owned(), "bar".to_owned()];
    let x2: Vec<_> = x.iter().map(|x| x.as_str()).collect();

    match x2.as_slice() {
        ["foo", y] => println!("y is {}.", y),
        _ => unreachable!(),
    }
}

请注意,您必须将 转换Vec为切片本身 ( x2.as_slice()),因为切片模式只能理解切片。

于 2015-11-22T19:51:41.710 回答