我可以直接匹配一个生锈的字符串,正如我们在这个例子中看到的那样.
let a = "hello".to_string();
match &a[..] {
"hello" => {
println!("Matches hello");
}
_ => panic!(),
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我有一个选项类型,它会失败.
match Some(a) {
Some("hello") => {
println!("Matches some hello");
}
_ => panic!(),
}
Run Code Online (Sandbox Code Playgroud)
因为类型不匹配.
error[E0308]: mismatched types
--> src/main.rs:5:14
|
5 | Some("hello") => {
| ^^^^^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
Run Code Online (Sandbox Code Playgroud)
我无法做到这一点,String因为我们有一个[..].到目前为止,我提出的最好的是:
match Some(a) {
Some(b) => match (&b[..]) {
"hello" => {
println!("Matches some, …Run Code Online (Sandbox Code Playgroud)