我在看Rust
官网提供的例子是Mutex<u32>
类型的实现方式,但是当我改成Mutex<String>
类型想要修改他的值时,惊喜
就出现了,无法编译通过,下面是的代码:
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
let message = Arc::new(Mutex::new(String::from("hello")));
let mut handles = vec![];
for i in 0..10 {
let message = Arc::clone(&message);
let handle = thread::spawn(move || {
let mut message_ = message.lock().unwrap();
*message =format!("hello {}", i);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *message.lock().unwrap());
}
错误信息如下所示:
error[E0308]: mismatched types
--> src/main.rs:13:23
|
13 | *message =format!("hello {}", i);
| ^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::sync::Mutex`, found struct `std::string::String`
|
= note: expected type `std::sync::Mutex<std::string::String>`
found type `std::string::String`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
通过查阅资料,最终发下只要把let mut message_ = message.lock().unwrap()
改为let mut message = message.lock().unwrap()
就完美解决了,在学习Rust
的路上会遇到各种坑,唯有苦练记录再温习方可进一步深入理解Rust
设计之精美。