These are chat archives for rust-lang/rust

15th
Sep 2017
David Harvey-Macaulay
@alteous
Sep 15 2017 08:18
Can I have a mutable lazy static?
David Harvey-Macaulay
@alteous
Sep 15 2017 08:19
@ozkriff Thanks!
David Harvey-Macaulay
@alteous
Sep 15 2017 08:42
Actually, lazy_static isn't solving my problem. Is there a simple, thread-safe way of writing to a String without passing Mutex<String> into every function?
Ideally I'd like to be able to call one of the logging macros and redirect to a String variable instead of stdout.
Denis Lisov
@tanriol
Sep 15 2017 09:02
I'm afraid multiple threads appending to a single string cannot be done without locking of some kind. Why not Mutex?
David Harvey-Macaulay
@alteous
Sep 15 2017 09:06
@tanriol Sorry, I'm mistaken. @ozkriff 's suggestion does solve my problem, I was just running into a compile error that led me astray. Below is working as intended.
pub mod console {
    use std::sync::Mutex;

    lazy_static! {
        static ref TEXT: Mutex<String> = Mutex::new(String::new());
    }

    pub fn contents() -> String {
        TEXT.lock().unwrap().clone()
    }

    pub fn clear() {
        TEXT.lock().unwrap().clear();
    }

    pub fn println(message: &str) {
        let mut text = TEXT.lock().unwrap();
        if !text.is_empty() {
            text.push('\n');
        }
        text.push_str(message);
    }
}