从产生线程的函数返回值

时间:2019-08-25 19:20:27

标签: rust

我正在尝试在线程中使用pop()返回Sting:

use std::sync::{Arc, Mutex};
use crossbeam_utils::thread;

pub struct MyText {
    my_text: Mutex<Vec<String>>,
}

pub trait MyTextOptions {
    fn get(&self) -> String;
}

impl MyTextOptions for MyText {
    fn get(&self) -> String {
        let mut int_text = Arc::new(self);
        thread::scope(|scope| {
            scope.spawn(|_| {
                let mut text_feed = int_text.my_text.lock().unwrap();
                text_feed.pop().unwrap()
            });
        }).unwrap()
    }
}

当我尝试运行它时,我得到:

error[E0308]: mismatched types
  --> src\buffer.rs:50:9
   |
48 |       fn get(&self) -> String {
   |                        ------ expected `std::string::String` because of return type
49 |           let mut int_text = Arc::new(self);
50 | /         thread::scope(|scope| {
51 | |             scope.spawn(|_| {
52 | |                 let mut text_feed = int_text.my_text.lock().unwrap();
53 | |                 text_feed.pop().unwrap()
54 | |             });
55 | |         }).unwrap()
   | |___________________^ expected struct `std::string::String`, found ()
   |
   = note: expected type `std::string::String`
              found type `()`

我不明白为什么它不返回String中弹出的text_feed.pop().unwrap()值。

1 个答案:

答案 0 :(得分:1)

第一个问题如下:

            text_feed.pop().unwrap()
        });

但是您想要,为了返回某个表达式,因此您应该删除;。 完成后,您遇到了第二个问题,thread::scope的返回值将为crossbeam_utils::thread::ScopedJoinHandle类型,但您需要一个Stringdocs声明它有一个join()

放在一起,我们得到:

extern crate crossbeam_utils;

use std::sync::{Arc, Mutex};
use crossbeam_utils::thread;

pub struct MyText {
    my_text: Mutex<Vec<String>>,
}

pub trait MyTextOptions {
    fn get(&self) -> String;
}

impl MyTextOptions for MyText {
    fn get(&self) -> String {
        let int_text = Arc::new(self);
        thread::scope(|scope| {
            scope.spawn(|_| {
                let mut text_feed = int_text.my_text.lock().unwrap();
                text_feed.pop().unwrap()
            }).join().unwrap()
        }).unwrap()
    }
}