Understand reference parameters comparison — How to Rust

Ly Channa
2 min readMar 23, 2024

--

In Rust, reference parameters are sometimes used to compare values without explicitly using dereference operators due to Rust’s automatic dereferencing during comparisons. This feature of Rust, known as “deref coercion,” simplifies code and makes it more readable by reducing the need for explicit dereferences.

Deref coercion allows a reference to be automatically converted to another reference of a different type for operations that require a specific type. This conversion is performed by the Deref trait, which is implemented by many types in the Rust standard library, including smart pointers like Box<T>, Rc<T>, and Arc<T>, as well as references themselves.

Here’s why this is particularly useful:

Simplified Syntax

Automatic dereferencing makes the code more concise and easier to read. Without it, you would need to explicitly dereference references every time you want to compare their underlying values, which can clutter the code and make it harder to understand at a glance.

Consistency with Value Comparison

It allows for a consistent comparison syntax between values and references. Whether you’re comparing values directly or through references, the syntax remains the same, making the code more uniform and predictable.

Seamless Integration with Methods

When calling methods on objects, deref coercion allows you to call a method on a reference as if it were the underlying object itself. This is particularly useful when working with types that encapsulate or manage other types.

Here’s an example to illustrate automatic dereferencing in comparisons:

let x: i32 = 5;
let y: &i32 = &10;
// Automatic dereferencing allows us to compare these directly
if x < *y {
println!("x is less than y");
} else {
println!("x is not less than y");
}
// Because of automatic dereferencing, you can also write it without explicit dereference
if x < y {
println!("x is less than y");
} else {
println!("x is not less than y");
}

In the comparison x < y, even though y is a reference to an i32, Rust automatically dereferences y to compare its underlying value with x. This automatic dereferencing is part of Rust's efforts to make the language both safe and ergonomic by reducing boilerplate code and potential sources of error, such as incorrect manual dereferencing.

--

--

Ly Channa

Highly skilled: REST API, OAuth2, OpenIDConnect, SSO, TDD, RubyOnRails, CI/CD, Infrastruct as Code, AWS.