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.

7
  • 1
    type that implement copy are not moved but copied. play.rust-lang.org/… <= "I have tried the above code with integers and strings" press X to doubt Commented Nov 27, 2019 at 0:07
  • 1
    Does this answer your question? How does Rust provide move semantics? Commented Nov 27, 2019 at 0: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? Commented Nov 27, 2019 at 0: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 doc.rust-lang.org/book/ch08-02-strings.html#what-is-a-string Commented Nov 27, 2019 at 1:35
  • 1
    Perfect thanks, Stargateur Commented Nov 27, 2019 at 1:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Okay thanks, Where to find the documentation for that, like I want to know what traits are included with what types?
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 doc.rust-lang.org/std/marker/trait.Copy.html
have been looking into it. Just got confused with a few stuff. I guess I am getting it. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.