Skip to content

Latest commit

 

History

History
73 lines (48 loc) · 2.1 KB

11.md

File metadata and controls

73 lines (48 loc) · 2.1 KB

Pointers

pointers are generally, a variable that contains and address in memory where the address points to some data.

Smart Pointers

Box

the box pointer allows us to allocate data on the heap rather on the stack. however the pointer to the heap data remains on the stack.

// created a new tuple ; on the stack
let t = (12, "eggs");
// created a new box in the heap, but b remains in the stack
let b = Box::new(t);

RC - Reference Counting

RC also allocated on the heap, tracks references to evaluate whether an item is still in use.

ARC - Atomic Reference Counting

ARC are used for safe sharing between threads. Only use Arc when sharing the pointer between threads.

use std::rc::Rc;

let s1 = Rc::new(String::from("Pointer"));
let s2 = s1.clone();
let s3 = s2.clone();

In this example, we have a reference counter value pointed to a heap allocated string which will have a reference count.

a reference count keeps tracks of the number of references or pointers to a value int the heap. cloning a reference counter does not copy the value, it however creates a new pointer to the value.

Interior MMutability pattern

Interior mutability is a pattern where we mutate data even when there are immutable references to that data, although this is not allowed, this scenario uses rust's unsafe code to bend the rules of borrowing.

Ref Cell

RefCell is typically used when you want to mutate data that is behind an immutable reference.

use std::cell::RefCell;

struct Flagger {
    is_true: RefCell<bool>,
}

let flag = Flagger {
    is_true: RefCell::new(true),
};

let reference = flag.is_true.borrow();
println!("{}", reference);

// panics as already borrowed above
let mut mut_ref = flag.is_true.borrow_mut();
*mut_ref = false;
println!("{}", mut_ref);

Difference

  • RC - enables multiple owners of a reference

  • Box and RefCell allows on a single owner

  • Box - allows mutable or immutable borrows checked at compile time.

  • RC - allows only `'immutable' borrows checked at compile time

  • RefCell - allows immutable or mutable borrows checked at runtime.