1

This works fine:

fn main() {
    let mut mystr = "this is my string";
    println!("{}", mystr);
    mystr = "new string";
    println!("{}", mystr);
}

This does not work:

fn change(s: &mut str) {
    s = "new string";
    println!("{}", s);
}

fn main() {
    let mut mystr = "change me";
    //change(mystr);
    //change(&mystr);
    //change(&mut mystr);
}
error[E0308]: mismatched types
 --> src/main.rs:2:9
  |
2 |     s = "new string";
  |         ^^^^^^^^^^^^ types differ in mutability
  |
  = note: expected mutable reference `&mut str`
                     found reference `&'static str`

I don't know if I'm making a mistake or if the borrow checker is stopping it. The compiler errors don't really tell me.

I've tried the 3 different ways of passing the variable as the compiler error changes and sometimes says trying to pass &str to &mut str and when I change it to &mut mystr I get a new error.

Am I making a mistake or is this not allowed?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1003967
  • 137
  • 2
  • 11
  • 2
    Does [What's the difference between placing "mut" before a variable name and after the ":"?](https://stackoverflow.com/q/28587698/155423) answer your question? – Shepmaster Dec 07 '21 at 20:03
  • https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=84aa41febf9be97ed2a41e3aae220970 – Shepmaster Dec 07 '21 at 20:05
  • Thanks for the example. ive been working through the examples on the try it yourself and i thought i had a basic grasp of the borrowing system but i must have missed this, i cant understand it either. i dont know why i need & before mut and &before str. I thought Variable = was a constant, &variable = reference to constant, &mut variable = reference to a mutable what is &mut &str or have i just got confused becauise its &str for a slice, is &mut &str just the same as &mut int ? – user1003967 Dec 07 '21 at 20:21
  • Your last statement is exactly correct - `&str` is a string slice, and `&mut &str` is just like `&mut AnyOtherType`. – user4815162342 Dec 07 '21 at 21:00
  • Does this answer your question? [What's the difference between placing "mut" before a variable name and after the ":"?](https://stackoverflow.com/questions/28587698/whats-the-difference-between-placing-mut-before-a-variable-name-and-after-the) – Chayim Friedman Dec 07 '21 at 21:29

1 Answers1

0

I added the type to your first example to highlight what's happening.

fn main() {
    let mut mystr: &'static str = "this is my string";
    println!("{}", mystr);
    mystr = "new string";
    println!("{}", mystr);
}

Here's your second example. I changed the type of the s argument and added a *.

fn change(s: &mut &'static str) {
    *s = "new string";
}

fn main() {
    let mut mystr = "change me";
    println!("{}", mystr);
    change(&mut mystr);
    println!("{}", mystr);
}
NovaDenizen
  • 5,089
  • 14
  • 28