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
}