'When do I need to use a dereference in rust?
In the following example we are using a reference to self
in the println!
and show_type
functions yet we aren't dereferencing self
with *
to get the value.
Why aren't we using dereference in the example?
When do we need to use a dereference?
How can we print to screen if a variable is holding a reference or a value?
struct Animal<T> {
name: T,
}
impl<T: Display> Animal<T> {
fn show_type(&self) {
println!("{}", self.name);
println!("{}", type_name::<T>());
}
}
fn main() {
let dog = Animal {
name: String::from("Rex")
};
dog.show_type(); // Result: Rex, alloc::string::String
}
Solution 1:[1]
Field access expressions do automatic dereferncing in Rust: https://doc.rust-lang.org/reference/expressions/field-expr.html#automatic-dereferencing
And so I guess you would dereference manually when you need a whole value, not a specific field.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | freakish |