OK, I'm new. I have to keep a string between calls to a function. The string may change in a call, and the new value is used in the following call. After many attempts to make it simple, I've ended up with this test program:
use lazy_static::{lazy_static, __Deref};
use std::sync::Mutex;
lazy_static! {
static ref MY_STRING: Mutex<String> = Mutex::new(String::from("ABCDEF"));
}
fn main() {
fun();
fun();
fun();
}
fn fun() {
let mut string = MY_STRING.lock().unwrap();
println!("{}", string);
if string.deref() == "ABCDEF" {
*string = "Hello".to_string();
}
else if string.deref() == "Hello" {
*string = "world".to_string();
}
}
It works. I know I could use thread_local!
with RefCell
instead of lazy_static!
with Mutex
.
Is there no common, simple way to maintain a mutable string? In C, for example, I would simply add static
to a string declaration, e.g., static char myString[100]
, and access the static mutable myString
as any other character vector.