Why can't compile?

I am learning Rust and came across the following code

fn main() {
  let x = String::from("hello");
  x;                        // A
  println!("{}",x);     // error value borrowed here after move

It seems that x is moved at A. How does this happen? Many thanks.

It is moved because you used it in an expression that consumed it.

Have to accept it. Though a little anti-intuition. :upside_down_face:

Maybe, but I ask myself, what is your expectation if you write x;. Would you think, that that is a noop?

IMHO, the compiler could have a better error message, like:

Your statement doesn't do anything. Consider removing it

but yeah... What do you expect is the question.

thanks. If there is no such anti-intuition the following code will leak

fn test() -> String {
fn main() {

I think I understood it. Change the error message will be a good solution.

I mean, x; will always be a bit weird, but yes, it works on the same principle as your test();.

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.