Moving values into a function call, has there been changes to the language spec?

New to Rust and trying to get up to speed. Have been doing a Udemy course in which the lecturer specifically states that this code should fail, because s1 has been 'moved' into the function and hence no longer available.

fn main() {
    let s1 = 5;
    print_my_num(s1);
    println!("{}",s1); /// TOLD THIS SHOULD FAIL
}

fn print_my_num(q:i32) {
    println!("{}",q);
}

However, the code compiles and runs and I get two '5s' printed.

I'm wondering, has the language/compiler changed to allow this since the Udemy course was made about a year ago? Thanks.

The reason this works is that integers are Copy, so the ownership rules do not really apply to them in the same way they do to more complicated types. Try with the type String instead:

fn main() {
    let s1 = "My string".to_string();
    print_my_num(s1);
    println!("{}",s1); // THIS FAILS
}

fn print_my_num(q:String) {
    println!("{}",q);
}
error[E0382]: borrow of moved value: `s1`
 --> src/main.rs:4:19
  |
2 |     let s1 = "My string".to_string();
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     print_my_num(s1);
  |                  -- value moved here
4 |     println!("{}",s1); // THIS FAILS
  |                   ^^ value borrowed here after move
  |

As for whether this has changed recently, no.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.