在对文档Arc<T>说:
Arc<T>自动解引用T(通过Deref特征),因此你可以调用T类型值的方法Arc<T>.
但有没有办法允许匹配Option-al类型?
这是一个简单的例子:
use std::sync::Arc;
fn main() {
let foo: Arc<Option<String>> = Arc::new(Some("hello".to_string()));
if foo.is_some() {
println!("{}", foo.unwrap());
}
match foo {
Some(hello) => {
println!("{}", hello);
}
None => {}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器错误是:
error[E0308]: mismatched types
--> src/main.rs:11:9
|
11 | Some(hello) => {
| ^^^^^^^^^^^ expected struct `std::sync::Arc`, found enum `std::option::Option`
|
= note: expected type `std::sync::Arc<std::option::Option<std::string::String>>`
found type `std::option::Option<_>`
error[E0308]: mismatched types
--> src/main.rs:14:9
|
14 | None => {}
| ^^^^ expected struct `std::sync::Arc`, found enum `std::option::Option`
|
= note: expected type `std::sync::Arc<std::option::Option<std::string::String>>`
found type `std::option::Option<_>`
Run Code Online (Sandbox Code Playgroud)
不,你不能在一个Option内部匹配Arc.要在模式匹配中使用类型,必须可以使用该类型的实现,但实现Arc不是公共的.
在某些情况下,您可以执行某种转换以匹配引用.
例如,由于Arc<T>implements Deref,您可以使用*运算符通过Arc<T>底层取消引用T.由于这种匹配有一些符合人体工程学的语法,因此您可以在Option不获取所有权的情况下对其中的值进行引用:
match *foo {
Some(ref hello) => {
println!("{}", hello);
}
None => {}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用Option::as_ref将&Option<T>(从通道自动取消引用)转换为:Arc<T>DerefOption<&T>
match Option::as_ref(&foo) {
Some(hello) => {
println!("{}", hello);
}
None => {}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,你不能只是调用.as_ref()因为trait方法AsRef::as_ref优先.
在这两种情况下,if let如果您只关心其中一个匹配臂,那么使用它会更加惯用:
if let Some(ref hello) = *foo {
println!("{}", hello);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
843 次 |
| 最近记录: |