January 2019
Beginner to intermediate
554 pages
13h 31m
English
The concept of borrowing is there to circumvent the restrictions with the ownership rule. Under borrowing, you don't take ownership of values, but only lend data for as long as you need. This is achieved by borrowing values, that is, taking a reference to a value. To borrow a value, we put the & operator before the variable & is the address of operator . We can borrow values in Rust in two ways.
Immutable borrows: When we use the & operator before a type, we create an immutable reference to it. Our previous example from the ownership section can be re-written using borrowing:
// borrowing_basics.rs#[derive(Debug)]struct Foo(u32);fn main() { let foo = Foo; let bar = &foo; println!("Foo is {:?}", foo); println!("Bar is {:?}", bar); ...Read now
Unlock full access