- The code below can work.
#[derive(Debug)]
struct Test{
str1 : Option<String>,
str2 : Option<String>,
}
fn main() {
let mut test = Test{
str1 : Some(String::from("str1")),
str2 : Some(String::from("str2"))
};
let str1 = test.str1.as_mut().unwrap();
let str2 = test.str2.as_mut().unwrap();
*str1 = String::from("nonono1");
*str2 = String::from("nonono2");
println!("{:?}", test);
}
- The code with Arc<Mutex<>> like this can work.
use std::sync::{
Arc, Mutex
};
#[derive(Debug)]
struct Test{
str1 : Option<String>,
str2 : Option<String>,
}
fn main() {
let test = Test{
str1 : Some(String::from("str1")),
str2 : Some(String::from("str2"))
};
let test = Arc::new(Mutex::new(test));
let mut test = test.lock().unwrap();
let str1 = test.str1.as_mut().unwrap();
*str1 = String::from("nonono1");
let str2 = test.str2.as_mut().unwrap();
*str2 = String::from("nonono2");
println!("{:?}", test);
}
- But the other code cannot work.
use std::sync::{
Arc, Mutex
};
#[derive(Debug)]
struct Test{
str1 : Option<String>,
str2 : Option<String>,
}
fn main() {
let test = Test{
str1 : Some(String::from("str1")),
str2 : Some(String::from("str2"))
};
let test = Arc::new(Mutex::new(test));
let mut test = test.lock().unwrap();
let str1 = test.str1.as_mut().unwrap();
let str2 = test.str2.as_mut().unwrap();
*str1 = String::from("nonono1");
*str2 = String::from("nonono2");
println!("{:?}", test);
}
- It seems that I cannot borrow two deffierent part of a Struct wrapped in Arc<Mutex<>>.And I can do this in the first code.
I want to mutably borrow two parts of a structure wrapped with Arc<Mutex<>> at the same time. Is this possible?