Volatile data in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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