< 返回版块

leslieDD 发表于 2021-05-14 17:05

    let t2 = thread::spawn(|| {
        println!("thread t2");
        // 这儿要怎么写,可以返回一个Err,让下面的match进入到Err分支
    });
    match t2.join() {
        Err(e) => {
            println!("e: {:?}", e);
        }
        Ok(o) => {
            println!("o: {:?}", o);
        }
    }

t2线程里面要怎么写,可以返回一个错误,让之后的match进入到Err分支

评论区

写评论
c5soft 2021-05-14 22:01

需要注意的是:第一个Err分支不是程序调用的返回值,而是join失败了,第二个Err分支才是程序执行的错误分支

c5soft 2021-05-14 21:57

源代码 main.rs

use std::error::Error;
use std::fmt;
use std::thread;

#[derive(Debug)]
struct MyError {
    reason: String,
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MyError:{}", self.reason)
    }
}

impl Error for MyError {}

fn task(return_err: bool) -> Result<String, MyError> {
    if return_err {
        Err(MyError {
            reason: "bad".to_string(),
        })
    } else {
        Ok("good".to_string())
    }
}
fn main() {
    let true_or_false = std::env::args().nth(1).unwrap_or("false".to_string());
    let true_or_false = if true_or_false == "true" { true } else { false };

    let t = thread::spawn(move || task(true_or_false));
    match t.join() {
        Err(e) => {
            println!("join error: {:?}", e);
        }
        Ok(result) => match result {
            Ok(result) => {
                println!("Ok:{}", result);
            }
            Err(e) => {
                println!("Err:{}", e);
            }
        },
    }
}

编译执行:

cargo r -- true
显示:Err:MyError:bad

cargo r -- false
显示:Ok:good

作者 leslieDD 2021-05-14 17:16

哇,神了

--
👇
uno: ```rust let t2 = thread::spawn(|| { println!("thread t2"); panic!(); });


uno 2021-05-14 17:11
    let t2 = thread::spawn(|| {
        println!("thread t2");
        panic!();
    });
1 共 4 条评论, 1 页