What does this "*" do in rust

In this specific case what does "*" do

fn main() {
  let mut num: u32 = 3;
  edit(&mut num);
}

fn edit(num: &mut u32) {
  let new_num: u32 = 10;
  *num = new_num;
}



It dereferences num so you assign to the place in memory it points into (the num variable in main()) and not to the num variable.

The left-hand-side and right-hand-side of the assignment must be of the same type. If you didn't have the *, then the left-hand-side would be a &mut u32 but the right-hand-side would be an u32, which are not the same thing.

So basically "*" convert a &mut u32 to u32
Is i am correct?

To answer the question of what the * does in this case: It takes value of type &mut u32 and “returns” a place of type u32. Typical other examples of places include

  • local variable names
  • field access (x.foo)
  • array/slice index expressions (a[i])

Basically you can work with *num in many ways like with a local (mutable) variable of type u32 including assigning to it (as in your code example) or reading from it (e. g. let foo: u32 = *num;) or creating a reference to it (let r: &u32 = &*num).

Note that the deteferencing operator supports all kinds of reference / pointer types, not just &mut T, but also &T or Box<T> and more. It is even available for custom types, with behavior defined by the Deref and DerefMut traits.

4 Likes

Yes, the asterisk will dereference, which removes one layer of reference.

Okay, my confusion is finally cleared

I think you got it, but I just wanted to point out that convert is not really the right word to use here.

Dereferencing is more like: follow the reference to the underlying type.

1 Like

I love this explanation and wish I would have found it somewhere else before! Have been twisting my mind trying to find the proper words to explain it since beginning Rust. Thanks for the insight!

Edit: previously have tried to explain it as "The expression writes to that location in memory" but explaining it as a "a place of type" just makes more sense.

1 Like

For more details, see here: Expressions - The Rust Reference

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.