Skip to content

Instantly share code, notes, and snippets.

Created March 10, 2020 10:32
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)) };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment