1

my understanding is that declaring a string variable like the following

let x = "a string"

allocates memory for immutable x on the stack

while declaring x like this

let x = String::from("a string");

does the same but on the heap. And this way we create a mutable string variable.

My question is this, is there any difference between the following:

let mut x = "a string";

and

let x = String::from("a string");

doesn't this mean that in both cases x is a mutable string variable? can I assign x to another variable as in "y = x"?

trincot
  • 317,000
  • 35
  • 244
  • 286
krabbos
  • 47
  • 4
  • my question is a little different – krabbos May 04 '18 at 11:52
  • 2
    @krabbos Your question is phrased a bit differently, but the answer is: _one creates a `String` and the other creates a `&'static str`_. Which then leaves the question: _what's the difference?_ – Peter Hall May 04 '18 at 11:58
  • 1
    Shades of [What's the difference between placing “mut” before a variable name and after the “:”?](https://stackoverflow.com/q/28587698/3650362). `let mut x = "a string"` doesn't make `x` a `&'static mut str` – trent May 04 '18 at 12:50
  • 1
    Note: duplicate don't mean the same question but the same answer... – Stargateur May 04 '18 at 15:40
  • `let mut x = "a string";` declares a mutable variable that holds a borrow to immutable content `&str`. For example, the following will compile: `let mut x = "a string"; x = "hi";` However, if you remove the `mut` you will get the error "cannot assign twice to immutable variable `x`" The type `&mut str` needs to have something with a mutable backing like `String`. For example notice that in the docs https://doc.rust-lang.org/std/primitive.str.html all methods that take `&mut self` have examples using `String`. – rokob May 04 '18 at 15:44

0 Answers0