Sharing mutable data

I am writing a tool, where logging is a mechanism that's used by all parts of the tool but centrally stored.
this is how i handle draw, networking and logging.

struct log <'a> {
    messages: &'a mut Vec<String>,
}
struct draw <'a> {
    i: u32,
    l: &'a mut log<'a>,
}
struct net <'a> {
    i: u32,
    l: &'a mut log<'a>,
}

draw and networking, uses logging as a reference, as i have created methods centrally to log data and log file is also same for the entire liefcycle. However, according to Rust mutability and sharing design, I cannot implement this pattern. Is thers something I am missing, or is there another way of doing this?

You need to use some kind of internal mutability to make this work. Assuming that the only thing that draw and net are doing with log is to issue new messages, Iā€™d probably reach for a channel:

// call std::sync::mpsc::channel() to get a `Sender` and `Receiver`
// that are connected to each other.  The `Sender` can then be
// cloned as many times as you need.

struct Logger {
    unread: mpsc::Receiver<String>,
}

struct Draw {
    i: u32,
    l: mpsc::Sender<String>,
}

struct Net {
    i: u32,
    l: mpsc::Sender<String>,
}

1 Like