In the Rust programming language, a reference is a special data type that allows you to borrow another value without taking ownership of it. This is one of the core concepts of Rust's memory safety guarantees, enabling programs to avoid data races and dangling pointers at compile time.
Rust has two types of references:
-
Immutable Reference (
&T): An immutable reference allows you to borrow a value for reading but not for modification. Within any given scope, multiple immutable references can coexist because they do not interfere with each other. -
Mutable Reference (
&mut T): A mutable reference allows you to borrow and modify a value. According to Rust's rules, if you have a mutable reference, no other mutable references or immutable references can point to the same value within the same scope, preventing data races.
Example Explanation
Assume we have a struct Book, and we want to implement a function to modify its page_count attribute:
ruststruct Book { title: String, page_count: u32, } fn add_pages(book: &mut Book, pages: u32) { book.page_count += pages; }
In this example, the add_pages function accepts a mutable reference &mut Book, allowing it to modify the state of the passed Book instance. We increase the book's page count using book.page_count += pages;. When calling this function, ensure that a mutable reference is passed:
rustlet mut my_book = Book { title: String::from("Rust Programming"), page_count: 120, }; add_pages(&mut my_book, 20);
Note that when calling add_pages, we pass &mut my_book, which is a mutable reference. If my_book is not mutable, the compilation will fail because you cannot create a mutable reference from an immutable variable.
References in Rust are key to achieving efficient and safe code, allowing you to avoid unnecessary data copying while maintaining strict memory safety.