2

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 } 
0

2 Answers 2

5

Why aren't we using dereference in the example?

Because it's not necessary.

When do we need to use a dereference?

When the rust compiler does not auto-deref. Generally the rust compiler will auto-deref on attribute access and method calls (but only the "subject" of the call, parameters are not auto-deref'd). Though sometimes it's necessary to disambiguate.

How can we print to screen if a valubale is holding a reference or a value?

Because it's set up that way

impl<'_, T> Display for &'_ T where T: Display + ?Sized 

So there is an implementation of Display for any reference to something which implements Display, and it simply delegates through the reference.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.