乐闻世界logo
搜索文章和话题

What is a reference in Rust?

1个答案

1

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:

  1. 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.

  2. 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:

rust
struct 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:

rust
let 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.

2024年8月7日 14:05 回复

你的答案