rust 之 Arc - 2021-02-02

今天遇到了,读取Arc 类型变量值的问题,大概意思是这样的:

use std::sync::Arc;

fn main() {
    let foo: Arc> = 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>`
              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>`
              found type `std::option::Option<_>`

在网上查了查,果然有好办法:

match *foo {
    Some(ref hello) => {
        println!("{}", hello);
    }
    None => {}
}
// 或者:
match Option::as_ref(&foo) {
    Some(hello) => {
        println!("{}", hello);
    }
    None => {}
}
//  或者:
if let Some(ref hello) = *foo {
    println!("{}", hello);
}

// 或者:
if foo.is_some() {
        let f1: &Option = foo.as_ref();
        let f2: Option<&String> = f1.as_ref();
        let f3: &String = f2.unwrap();
        println!("{}", f3);

        println!("{}", foo.as_ref().as_ref().unwrap())
}

你可能感兴趣的:(rust 之 Arc - 2021-02-02)