如何打印由Mutex
和Arc
封裝的Vec
的值?我對Rust很新,所以我不確定我是否說得好。打印電弧和互斥鎖類型
這是我的代碼,鬆散地基於文檔。
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(vec![104, 101, 108, 108, 111]));
for i in 0..2 {
let data = data.clone();
thread::spawn(move || {
let mut data = data.lock().unwrap();
data[i] += 1;
});
}
println!("{:?}", String::from_utf8(data).unwrap());
thread::sleep_ms(50);
}
編譯器給我的錯誤:
$ rustc datarace_fixed.rs datarace_fixed.rs:14:37: 14:41 error: mismatched types: expected
collections::vec::Vec<u8>
, foundalloc::arc::Arc<std::sync::mutex::Mutex<collections::vec::Vec<_>>>
(expected structcollections::vec::Vec
, found structalloc::arc::Arc
) [E0308] datarace_fixed.rs:14 println!("{:?}", String::from_utf8(data).unwrap());