yushang
1
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.
alice
2
It is moved because you used it in an expression that consumed it.
yushang
3
Have to accept it. Though a little anti-intuition. 
hellow
4
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.
yushang
5
thanks. If there is no such anti-intuition the following code will leak
fn test() -> String {
String::from("hello")
}
fn main() {
test();
}
I think I understood it. Change the error message will be a good solution.
alice
6
I mean, x; will always be a bit weird, but yes, it works on the same principle as your test();.
system
Closed
7
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.