Rust Tutorial: Ownership and References in Rust
Understand ownership, borrowing, and references in Rust.
Concepts in this chapter
You will learn and practice:
- **Ownership** — each value has one owner; assignment moves ownership
- **Borrowing** — `&T` immutable reference, `&mut T` mutable reference
- **References** — don't take ownership; can have many `&` or one `&mut`
- **Dereference** — use `*ref` to get the value (or use . methods that do it)
- **No null** — use Option<T> for optional values
---
References
```rust
let s = String::from("hello");
let r = &s; // borrow; s still owns
println!("{}", r);
```
---
Mutable Reference
```rust
let mut x = 10;
let r = &mut x;
*r += 1;
println!("{}", x); // 11
```
---
Option
```rust
let maybe: Option<i32> = Some(42);
if let Some(n) = maybe {
println!("{}", n);
}
```
---
What's Next?
Next: **Structs** — define your own types.
What you'll learn in this Rust ownership and references in rust tutorial
This interactive Rust tutorial has 3 hands-on exercises. Estimated time: 15 minutes.
- Immutable Reference — Create a String `s = String::from("hello")`. Create an immutable reference `r = &s` and print using r.
- Option — Declare `let maybe: Option<i32> = None`. If it is Some(n), print n; otherwise print "none".
- Mutable Reference — Create `let mut x = 10`. Take a mutable reference `let r = &mut x`, add 1 through r (*r += 1), then print x.
Rust Ownership and References in Rust concepts covered
- Concepts in this chapter
- References
- Mutable Reference
- Option
- What's Next?