Confused on passing mut variable to function

Hello all

I'm confused on why we need to cast f2 to '&mut' when calling 'convert' function
and why not just '&' bec f2 is already defined as mutable.

fn convert(f: &mut String) -> bool {
    true
}

fn main() {
    let mut f2 = String::from("f1.txt");
    convert(&mut f2);   // why cast to mut here since f2 is already defined as mut ?

The type of f2 is String, not &mut String. You have a mutable binding, but it's a value, not a mutable reference.

So when call convert(&mut f2) from the main the value of f2 is bound to parameter f of convert
and its binding has to match how binding is defined in the parameter of convert(&mut f2)?

Here, let's break it down a bit. Let's pull that out into a temporary:

fn convert(f: &mut String) -> bool {
    true
}

fn main() {
    let mut f2 = String::from("f1.txt");
    let temp = &mut f2; 
    convert(temp);

This is the same thing as what you're doing. Now, let's annotate the types:

fn main() {
    let mut f2: String = String::from("f1.txt");
    let temp: &mut String = &mut f2; 
    convert(temp);

See how temp has the same time as the function requires? And how f2 is just a regular String?

Now, you may be asking "why do I need f2 to be mut?" The answer is basically "you can only take a &mut to something that's marked as mut, as a way to help you understand mutability in your program." It lets you know that f2 will be mutated somehow.

Does that make sense?

2 Likes

I think the misunderstanding i had was that i thought that & and mut are two separate thing in &mut, but it is one together a single operator, a mutable reference (&mut).

The mut on the left of : like in let mut f2: Stringis saying f2 is mutable.
But mut on the right of : can only come as &mut and it means that it is a mutable reference
to mutable variable.

is this understanding correct?

Also, thanks for taking time to help.
And also thanks to people fixing my english

1 Like

That’s correct!

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.