Arc<T>的文档中写到:
"Arc<T>会自动通过Deref trait转换成T,因此可以在类型为Arc<T>的值上调用T的方法。"
但是有没有一种方法可以匹配Option类型呢?
下面是一个简单的例子:
编译器错误为:
"Arc<T>会自动通过Deref trait转换成T,因此可以在类型为Arc<T>的值上调用T的方法。"
但是有没有一种方法可以匹配Option类型呢?
下面是一个简单的例子:
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 => {}
}
}
编译器错误为:
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<_>`
foo
(例如let f2 = (*foo).as_ref()
)比在Arc
上使用.as_ref
更符合惯用语。 - trent