I decided to turn on Expression Adjustment Hints inlay hints in Rust Analyzer, then I get confused about line 2. why is metadata being dereferenced then borrowed again. Since is_dir()
is acting on its reference ( pub fn is_dir(&self) -> bool
) and the parameter metadata
is already borrowed ( metadata: &Metadata
), isn't it redundant to dereference and borrow again? But since Rust Analyzer is displaying the inlay hints as (&*metadata).is_dir()
, I am wondering is it really like that under the hood?
It's a reborrow.
Calling functions with a reference can involve a reborrow, which is what the &*
or &mut *
is. It's usually not a significant change for shared references (&
, which implement Copy
), but crucial for exclusive references (&mut
, which do not).
For example this would not compile if not for reborrows.
fn example(v: &mut Vec<i32>) {
// reborrows
v.push(0);
// ownership of `v` was not lost
println!("{v:?}");
}
And the thing that a reborrow does is produce a reference whose lifetime is shorter than the original reference. Formally, &'a T
and &'b
T are different types and it is a specific feature of the language that you are allowed to use a long-lived reference as if it were a short-lived one without explicitly reborrowing all the time.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.