lazy_static 全局字符串不会打印

lazy_static global string will not print

我已经写了这段代码,但我一直有问题...字符串不会打印,我不知道我在这里做错了什么...

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

我不知道我哪里出错了我对这整个生锈的东西都是新手,但我知道我需要在这里使用一个全局可变变量 lazy_static 所以我需要它来工作......

example 不是字符串。它是一个包含 StringMutex。在访问其内容之前,您必须 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

Each mutex has a type parameter which represents the data that it is protecting. The data can only be accessed through the RAII guards returned from lock and try_lock, which guarantees that the data is only ever accessed when the mutex is locked.