Ownership and borrowing
In the previous section the word borrowed
was mentioned in most error messages. What's this all about? What is the logic behind this borrow checker mechanism?
Every program, whatever it does, like reading data from a database or making a computation, is about handling resources. The most common resource in a program is the memory space allocated to its variables. Other resources could be files, network connections, database connections, and so on.
Ownership
Every resource is given a name when we make a binding to it with let
; in Rust speak we say that the resource gets an owner. For example, in the following code snippet klaatu
owns the piece of memory taken up by the Alien
struct instance:
// see code in Chapter 7/code/ownership1.rs struct Alien { planet: String, n_tentacles: u32 } fn main() { let mut klaatu = Alien{ planet: "Venus".to_string(), n_tentacles: 15 }; }
Only the owner can change the object it points to, and there can only be...