我已经写了这段代码,但我一直遇到问题...字符串不会打印,我不知道我在这里做错了什么......
use lazy_static::lazy_static;
use std::io::{self, Write};
use std::sync::Mutex;
lazy_static! {
static ref example: Mutex<String> = Mutex::new("example string".to_string());
}
fn main(){
println!("{}", example);
}
我不知道我哪里出错了,我是整个 rust 事情的新手,但我知道我需要在这里使用全局可变变量lazy_static所以我需要它来工作......
example
不是字符串。这是一个包含String
的Mutex
。在访问互斥锁内容之前,您必须lock
互斥锁:
use lazy_static::lazy_static;
use std::io::{self, Write};
use std::sync::Mutex;
lazy_static! {
static ref example: Mutex<String> = Mutex::new("example string".to_string());
}
fn main(){
println!("{}", example.lock().expect("Could not lock mutes"));
}
来源:引用 https://doc.rust-lang.org/std/sync/struct.Mutex.html:
每个互斥锁都有一个类型参数,该参数表示它所在的数据 保护。数据只能通过 RAII 防护装置访问 从
lock
和try_lock
返回,这保证了数据是 仅在互斥锁锁定时访问。