Skip to content

Instantly share code, notes, and snippets.

@BruJu
Created March 10, 2020 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BruJu/3ab59baaea0eb00c9dfdf4e6c86f86d8 to your computer and use it in GitHub Desktop.
Save BruJu/3ab59baaea0eb00c9dfdf4e6c86f86d8 to your computer and use it in GitHub Desktop.
Volatile data in Rust
/// Code example of how to have mutable data in an object passed by ref
/// The use case of this snippet is to cache some computed data
use core::cell::RefCell;
struct Cat {
age: RefCell<Option<i32>>
}
fn display_age(cat: &Cat) {
if cat.age.borrow().is_none() {
let mut age_mut = cat.age.borrow_mut();
*age_mut = Some(7);
}
print!("The cat is {} yo\n", cat.age.borrow().unwrap());
}
fn main() {
let c = Cat { age: RefCell::new(None) };
let felix = Cat { age: RefCell::new(Some(88)) };
display_age(&c);
display_age(&felix);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment