Why we need to use mut in data types for borrowing?

fn main(){
   let mut x = String::from("foo-var");
   let a: &mut String = &mut x; //my question is about this
   let y = take_x(a);

   println!("{}",a);


}

fn take_x (val: &mut String) -> (){
   val.push_str("wo")
}

Why when i borrow a mutable variable, it requires the use of mut in the data type, such as &mut String? Even though it's already clear on the right-hand side that I want to borrow a mutable variable, namely x (&mut x). Does &String or &mut String get recognized by the compiler as a new data type, or is it merely a marker for a pointer?

&String and &mut String are different types.

Note that to be able to take a mutable borrow, the variable should be declared mut. I guess this is a safeguard to avoid accidentally calling &mut self methods with noticing:

let foo = Foo::new();
foo.method_that_mutates_foo();

you can omit the type on the left hand and the compiler will infer it for you, but if you do not omit, then the type must be correct. it's not just &mut String vs & String, it's true for any types, e.g.:

let x: i32 = 42i32; // x is inferred as `i32`
let y = x; // y is inferred as `i32` too,
let z: u32 = x; // error, z reqiures `u32` but got `i32`

I should add, the explicitly declared type and the actual type of the right hand side expression need NOT to be exactly the same, it's enough to be implicitly coercible.

I guess this might be the reason why you get confused, as &mut T can be coerced into &T.

this alone is valid:

   let a: &String = &mut x;

but when you add this call:

take_x(a)

you'll get a type error.

it is because the parameter val requires type &mut String, but you give it an argument a which has type &String.

1 Like

So, the purpose of having that type is just as a reference? Not as a new data type, right?

References are types.

1 Like

I think that by "reference" OP meant that type declarations are a "guide" for the compiler.

You may at times want a shared borrow of mut x too. Just because it's mutable doesn't mean that you want every reference to it to be &mut.

3 Likes