this post was submitted on 23 Aug 2023
17 points (100.0% liked)

Rust

6041 readers
9 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
 

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

top 5 comments
sorted by: hot top controversial new old
[–] [email protected] 4 points 1 year ago

You can wrap the Vec in a Mutex

[–] Barbacamanitu 2 points 1 year ago (1 children)

Maybe lazy_static? Personally I'd just pass a borrow to the vec around. It's very common for programs to have some global state that they pass around to different parts.

[–] [email protected] 1 points 1 year ago (1 children)

🤔 I thought lazy_static was deprecated in favor of one_cell

[–] Barbacamanitu 1 points 1 year ago* (last edited 1 year ago)

Ah I didn't realize most people have moved onto OnceCell. The issue with both lazy static and oncecell is that they can only be assigned to once. You need a global mutable state, so neither OnceCell or lazy_static are the right choice.

You're going to be fighting the borrow checker if you try to have global mutable state. It will bite you eventually. You can potentially use an interior mutablity pattern along with a mutex. Have you looked into interior mutability?

[–] [email protected] 2 points 1 year ago

Can't you just use the get_or_init method instead of get inside the push_log method? This would initialize the cell on first use. You'd still need a Mutex inside of it to acquire a mutable reference to the vector.