Type differ in mutability

Trying the below simple function:

fn test(x: &mut str) {
     x = "hello!";
     println!("{}");
}

And for the type differ in mutability error directly even before calling it or mentioning it any where.

The binding x is not mutable, so it can't be assigned at all. Declare it mut x: &... if you want to be able to reassign it.

The literal "hello" has type &'static str -- this is where it differs in mutability if you try to assign that to a value of type &mut str. The lifetimes also differ, but at least 'static is variant down to the implicit lifetime of your argument.

If you're trying to copy the contents of one string into another, well, you can't really do that into &mut str. That's borrowed memory, and can't be determined at compile time to have enough space for the string you're trying to assign. You probably should be passing &mut String instead, and then you can clear() and push_str("hello").

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.