Skip to content

Instantly share code, notes, and snippets.

@BruJu
Created Mar 10, 2020
Embed
What would you like to do?
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