In Rust, dereferencing with the dot operator (.
) is made possible through a feature known as auto-dereferencing. This feature allows you to access the fields and methods of the struct through a reference to that struct, without needing to manually dereference it.
Here's an explanation of how this works in your example:
struct Anime {
name: &'static str,
bechdel_pass: bool,
}
let aria = Anime {
name: "Aria: The Animation",
bechdel_pass: true,
};
let anime_ref = &aria;
assert_eq!(anime_ref.name, "Aria: The Animation");
When you use anime_ref.name
, Rust implicitly dereferences anime_ref
to get to the underlying Anime
struct, and then accesses the name
field. This auto-dereferencing happens because of the Deref
trait implementation in Rust's standard library.
Here is a more detailed breakdown of what's happening:
let anime_ref = &aria;
anime_ref
is a reference to the aria
instance of Anime
.anime_ref.name
anime_ref.name
, Rust automatically dereferences anime_ref
to access the name
field of the aria
struct.(*anime_ref).name
, but Rust simplifies it for you.The Deref
trait is what allows Rust to perform this automatic dereferencing. The standard library provides implementations of Deref
for references, allowing the compiler to automatically convert &T
to T
when accessing fields or calling methods.
Here's a simplified view of how the Deref
trait works:
use std::ops::Deref;
impl<T> Deref for &T {
type Target = T;
fn deref(&self) -> &T {
*self
}
}
This implementation allows &Anime
to be automatically dereferenced to Anime
when accessing fields or calling methods.
Auto-dereferencing also works with methods. For instance, if Anime
had a method, you could call it on a reference:
impl Anime {
fn description(&self) -> String {
format!("{}: {}", self.name, self.bechdel_pass)
}
}
let aria = Anime {
name: "Aria: The Animation",
bechdel_pass: true,
};
let anime_ref = &aria;
assert_eq!(anime_ref.description(), "Aria: The Animation: true");
Here, anime_ref.description()
works because Rust automatically dereferences anime_ref
to call the description
method.