WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 19 of 100

What is the difference between a reference and a pointer in Rust?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, references and pointers are used to refer to memory locations. However, there are some key differences between them.

1. Ownership and Borrowing

In Rust, every value has an owner, and only the owner has the authority to modify or destroy the value. Pointers, on the other hand, can be assigned and reassigned to different owners. References, however, are similar to pointers but are restricted to borrowing. A borrow is a temporary reference to a value owned by someone else. The borrower is not allowed to modify or destroy the value, only read it.

2. Nullability

By default, pointers in Rust can be null, meaning they do not point to any memory location. This can lead to runtime errors if not handled properly. References, however, are non-null by default since they must always refer to a valid memory location. In Rust, nullability can be explicitly defined using the ‘Option‘ type.

3. Syntax

In terms of syntax, pointers are represented using an asterisk ‘*‘ before the variable name, while references are represented using an ampersand ‘&‘ before the variable name. For example, ‘let x: *mut i32 = &mut 5;‘ defines a mutable pointer to an integer value, while ‘let y: &i32 = &5;‘ defines an immutable reference to an integer value.

4. Safety

Rust’s ownership and borrowing system ensure that references are always valid, as long as the owner remains alive. This helps prevent null pointer errors and other memory-related bugs commonly found in languages like C++. Additionally, Rust’s compiler enforces strict rules around reference lifetimes, ensuring that references cannot outlive their owners or be used after they have been dropped.

In summary, pointers and references in Rust have similar functionality, but references are safer and more restrictive while pointers are more flexible and powerful. In general, it is recommended to use references whenever possible in Rust, and only resort to pointers when strictly necessary.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics