Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The dereferencing operator * is used to access the value pointed to by a reference. Here is an example from Dereferencing:

true
()

The Box structure is a kind of pointer/reference, and accepts too the usage of the dereferencing operator * to access the original value thanks to the implementation of the Deref trait:

Couldn't automatically determine type of variable `b`.
Please give it an explicit type.

The Deref trait is implemented as following for a pointer type Foo<T>:

The deref() method returns a reference to the original value of type Target (i.e.: T), it does not actually dereference. Instead, what happens in our example above with the *b line is the following:

  1. The compiler sees that b is a type implementing Deref.

  2. It calls b.deref() and gets a reference on the original value.

  3. It applies the dereferencing operator * on this reference.

see solution

31.2.1Automatic Deref coercion

The Deref trait is implemented for multiple types in Rust. For instance the String type implements the Deref trait to allow the automatic conversion of &String into &str.

Let us see it in effect. First we create a function that accepts a &str:

Let us suppose now that we have a String inside a Box:

The following call works because:

  1. The Box implementation of the Deref trait allows the compiler to convert &x into a &String.

  2. The String implementation of the Deref trait allows the compiler to convert the &String into a &str.

31.2.2Method access

Thanks to the Deref trait we can also access methods that are defined inside the pointed objects.

Using this property, we can for instance call the to_uppercase() method of str onto the Box object x:

31.2.3DerefMut

There exists also a DerefMut trait that permits to dereference a mutable object.

Let us define a mutable Box object on a String:

We can call any method that modifies the internal string, like push_str(), on x:

Here is the result: