Rustlings: conversions/as_ref_mut exercise

Hi, I have just started learning Rust following the rustlings tutorial. I am having some trouble understanding as_ref_mut exercise, specifically reguarding this part:

// Squares a number using as_mut().
// TODO: Add the appropriate trait bound.
fn num_sq<T>(arg: &mut T) {
    // TODO: Implement the function body.
    ???
}

I have tried with the following:

// Squares a number using as_mut().
fn num_sq<T: AsMut<u32>>(arg: &mut T) {
    let v = arg.as_mut();
    *v = *v.pow(2);
}

Which gives compiler error:

error[E0614]: type `u32` cannot be dereferenced
  --> exercises/conversions/as_ref_mut.rs:23:10
   |
23 |     *v = *v.pow(2);
   |          ^^^^^^^^^

The following works instead:

fn num_sq<T: AsMut<u32>>(arg: &mut T) {
    let v = arg.as_mut();
    *v = *v * *v;
}

Could anyone tell me why I can't call the pow function on the dereferenced value?

In Rust, the method call operator (and other postfix operators) have higher precedence than the * dereference operator (and other prefix operators). Therefore, your code is equivalent to

*v = *(v.pow(2));

and is attempting to dereference the result of v.pow(2), which is not a reference but just a u32 (hence the error you got). To express what you intended, you would have to write

*v = (*v).pow(2);

but there is no need to do so, because method calls auto-dereference, so the simplest and idiomatic option is

*v = v.pow(2);
5 Likes

Thank you!

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.