Understanding Ownership

Ownership is the feature that makes Rust (and therefore Oxide) both safe and fast without a garbage collector. It determines when values are created, moved, borrowed, and dropped.

What You'll Learn

  • The ownership rules and how moves work
  • Borrowing with references and the rules that keep them safe
  • The slice type for working with parts of collections

A First Look

fn main() {
    let name = String.from("Oxide")

    // `name` moves into `owner`
    let owner = name

    // name is no longer valid here
    // println!("\(name)")

    let greeting = String.from("Hello")
    let length = stringLength(&greeting)
    println!("'\(greeting)' has length \(length)")
}

fn stringLength(text: &String): Int {
    text.len()
}

Ownership errors can feel strict at first, but they prevent entire classes of bugs at compile time. The next sections explain the rules in detail and show how to design programs around them.