Why does move occur here?

let mut s = String::from("a");
s; // <<<  moved here.

s.push_str("a");

compiler says s moved at s;.

I feel like this is basic knowledge, but where do I look?

This came up recently here: The expression without effect moves the variable - #3 by steffahn

I believe this fairly subtle corner of the language is not really adequately documented anywhere, but it's also not meant to be used (the compiler has a warning lint for it). If you want to explicitly drop something it's idiomatic to use drop(s).

2 Likes

It is similar to the example from the chapter of the book on ownership ( which doesn't compile ):

https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html

fn main() {
    let s1 = String::from("hello");
    let s2 = s1;

    println!("{}, world!", s1);
}

except here s1 was assigned to s2, whereas you simply moved s (by evaluating it) without doing anything with it ( which was kind-of odd ).

1 Like

It's highly logical and “kinda obvious” if you look on your program as on a piece of mathematics.

But people are not logical creatures, that's why it took centuries to discover and rediscover zero and why it takes years for newbies to accept that numbering should start at zero.

Similarly here: if you mention object in an expression without & or &mut (explicit or implicit) then it's content is “moved out” somewhere… even is said content is made “perpendicular to everything else” and thus disappears (like in Stranger in a Strange Land) like in simple s; case.

I suspect it's not documented anywhere because there's nothing to document, kinda: it's either “obvious and trivial” or “almost impossible to comprehend” depending on how you look on your program.

If you accept that program (any program!) is just The Glass Bead Game and have rules but that there are no intrinsic meaning[1] then it's “obvious and trivial”.

If you want for every program to have a meaning and couldn't accept that it's not a requirement then it's very hard to accept why such a meaningless and trivial use of object can make it disappear.

One would need a psychology degree to maybe write something worth adding to a tutorial, but such people wouldn't know Rust and are busy with other things…


  1. People often assign some meanings to various programs, but that's all in our head, program as it exists in the source or binary in a computer doesn't have any intrinsic meaning. ↩︎

2 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.