Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 16, 2018 15:49
Show Gist options
  • Save rust-play/152c71e1ea95961bd94428c8067730ed to your computer and use it in GitHub Desktop.
Save rust-play/152c71e1ea95961bd94428c8067730ed to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// Practice with Cell Smart Pointers
// Cells grant interior mutability:
// Cells allow you to mutate the interior value, these can only be used with
// values on the stack or Copy values
// RefCells allow you mutate the interior reference use this for values on the heap
// or Clone values
// RefCells provide the functions borrow() and borrow_mut() to retrieve mutable and
// immutable references to a value respectively
// Cells provide the functions get() and set() to directly retrieve and manipulate
// the underlying value.
// Because values are simply moved in and out of Cell types, you can have several
// "mutable" references to an object, because you can have:
// - Several immutable references to an object
// OR
// - One mutable reference to an object
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
#[test]
fn test_cells() {
let heap_data = RefCell::new(Data::new());
let mut test_data = Data::new();
let test_val =
test_data.x = 2;
test_data.y = 2;
let stack_data = Cell::new(10);
manipulate_heap_data(&heap_data);
manipulate_stack_data(&stack_data);
println!("heap_data = {:#?}", heap_data.borrow());
println!("stack_data = {:#?}", stack_data.get());
assert_eq!(heap_data.borrow().equals(&test_data), true);
assert_eq!(stack_data.get(), 20);
}
fn manipulate_heap_data(heap_data:&RefCell<Data>) {
// to manipulate a RefCell, you need to borrow a mutable copy of the data
// inside the cell
let mut val = heap_data.borrow_mut();
val.x *= 2;
val.y *= 2;
}
fn manipulate_stack_data(stack_data:&Cell<i32>) {
let mut val = stack_data.get();
stack_data.set(val * 2);
}
#[derive(Debug)]
struct Data {
x: i32,
y: i32,
}
impl Data {
fn new() -> Data {
Data {
x: 1,
y: 1,
}
}
fn equals(&self, data: &Data) -> bool{
self.x == data.x && self.y == data.y
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment