1

Given the code below:

let x = 5;
let y = x;
println!("{}", x);

As far as I have been reading, I learned that the above code would end up in error as the value of x has been moved to y. But it doesn't work that way. I have tried the above code with integers and strings, it just works.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Sumchans
  • 3,088
  • 6
  • 32
  • 59
  • 1
    type that implement copy are not moved but copied. https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cdca162a2aebe1c3921df6815195deff <= "I have tried the above code with integers and strings" press X to doubt – Stargateur Nov 27 '19 at 00:07
  • 1
    Does this answer your question? [How does Rust provide move semantics?](https://stackoverflow.com/questions/29490670/how-does-rust-provide-move-semantics) – Stargateur Nov 27 '19 at 00:08
  • @Stargateur, thanks for the speedy response, I tried let x = "hello" , the code worked and as you mentioned on your comment when I tried let x = String::new("Hello") it didn't. I guess i am getting whats wrong here. When it is let x = "hello", it is a str which will be in allocated memory and it has copy trait implemented, is that right? – Sumchans Nov 27 '19 at 00:55
  • 1
    `"hello"` is a `&'static str` it not allocated in the "heap" but directly "somewhere" depend on your OS etc. Anyway, reference implement copy so yes this work with reference. `&str` != `String` == View != Object https://doc.rust-lang.org/book/ch08-02-strings.html#what-is-a-string – Stargateur Nov 27 '19 at 01:35
  • 1
    Perfect thanks, Stargateur – Sumchans Nov 27 '19 at 01:39
  • @Sumchans it's called a [string slice](https://doc.rust-lang.org/std/primitive.str.html). And yes, they 'are Copy as well as primitive integers. – hellow Nov 27 '19 at 06:29
  • Does this answer your question? [Why can an integer variable still be used after assigning it to another variable?](https://stackoverflow.com/questions/74503570/why-can-an-integer-variable-still-be-used-after-assigning-it-to-another-variable) – mkrieger1 Nov 19 '22 at 20:58

1 Answers1

2

Primitives types by default implement Copy trait. So, in this case, value of x is copied into y. Try doing the same thing with anything that doesn't implement copy trait like String, you will encounter a compile time error. It is inefficient to create a copy every time you assign a variable to another variable. However, certain things can be trivially copied.

apatniv
  • 1,771
  • 10
  • 13
  • Okay thanks, Where to find the documentation for that, like I want to know what traits are included with what types? – Sumchans Nov 27 '19 at 01:26
  • See look at this documentation. This may be meaty but take some time to go through the documentation. It will clarify some of the stuff https://doc.rust-lang.org/std/marker/trait.Copy.html – apatniv Nov 27 '19 at 03:44
  • have been looking into it. Just got confused with a few stuff. I guess I am getting it. Thanks again. – Sumchans Nov 27 '19 at 18:25