How to modify mutex of String?

Hello community,

I fail to update a String Mutex:

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);

    for handle in handles {

    println!("Result: {}", *message.lock().unwrap());

Error is:

error[E0308]: mismatched types
  --> src/
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)

In book, example is with u32. It look like different for String.

How to modify this String Mutex ? Thank’s !


let mut message_ = message.lock().unwrap();


let mut message = message.lock().unwrap();

Oh! Thank you !

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.