Rust pointers

From wikinotes
Revision as of 00:19, 10 February 2023 by Will (talk | contribs) (Created page with "= Pointers/References = <blockquote> <syntaxhighlight lang="rust"> let foo = String::new("hi"); &foo // `&` get reference to foo let ref = &foo; *ref // `*` de-reference to get foo instance </syntaxhighlight> </blockquote><!-- Pointers/References --> = Smart Pointers = <blockquote> == Traits == <blockquote> * [https://doc.rust-lang.org/std/ops/trait.Deref.html Deref] alters how the de-reference operator (<code>*</code>) behaves * [https://doc.rust-lang.org/std/ops/...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Pointers/References

let foo = String::new("hi");
&foo   // `&` get reference to foo

let ref = &foo;
*ref   // `*` de-reference to get foo instance

Smart Pointers

Traits

  • Deref alters how the de-reference operator (*) behaves
  • DerefMut alters how the de-reference operator (*) behaves for mutable references
  • Drop alters the object's destructor, normally run when the object falls out of scope.

Box

Box types let you represent recursive types, where the total size is unknown at compile time,
by replacing your type with a pointer to it.

The docs use the example of a recursive enum.
An Enum's size is determined by it's largest possible value.
If an enum refers to an instance of itself the compiler is unable to determine it's size.

The box type allocates your object to the heap, and returns a pointer to it.
Pointers have a known size, so you can assign that instead.
Also, it implements the Deref trait, which allows you to use box as if it were a reference to the object you assigned to it.

#[derive(Debug)]
enum Path {
    Dir(String, Box<Path>),
    File(String),
}

impl Path {
    fn file(file: &str) -> Box<Path> {
        Box::new(
            Path::File(file.to_string())
        )
    }

    fn dir(dir: &str, path: Box<Path>) -> Box<Path> {
        Box::new(
            Path::Dir(dir.to_string(), path)
        )
    }
}

fn main() {
    let mypath = Path::dir("/var", Path::dir("/tmp", Path::file("/foo.txt")));
    dbg!(mypath);
}

Function Pointers