I’ve been trying to use OneCell, but I keep having errors trying to set it up to handle a mutable vector that I can push to.

I know there’s going to be some answers telling me maybe not to use a singleton, but the alternative of passing a vector all around throughout my code is not ergonmic at all.

I’ve tried lots of things, but this is where I’m at right now. Specifically I’m just having trouble initializing it.

`/**

  • LOG_CELL
  • Stores a vec of Strings that is added to throughout the algorithm with information to report
  • To the end user and developer */ pub static LOG_CELL: OnceLock<&mut Vec> = OnceLock::new();

pub fn set_log() { LOG_CELL.set(Vec::new()); }

pub fn push_log(message: String) { if let Some(vec_of_messages) = LOG_CELL.get() { let something = *vec_of_messages; something.push(message); } } `

  • frankfurt_schoolgirl [she/her]
    link
    fedilink
    English
    210 months ago

    Is the Singleton accessed by one thread or many?

    If it’s one thread, couldn’t you just wrap the Vec in an Rc and then clone your singleton every time you need it in a new scope?

    If it’s many, you should use channels and a dedicated logging thread imo.

    • @nerdbloodOP
      link
      110 months ago

      One for now, theoretically many later.

      Nice I’ve never used Rc. Maybe now’s my chance to look into it.

      • @[email protected]
        link
        fedilink
        3
        edit-2
        10 months ago

        Look into Arc, RwLock, and Mutex too.

        Later, check out parking_lot and co. and maybe async stuff too.

        • @nerdbloodOP
          link
          110 months ago

          Async I have a handle on, but I’ll take a look at the others for sure.