如何修改rust中Mutex<String>类型的值?

我在看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设计之精美。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值