Why Rust stop move out a value behind a a mutable reference

I'm new rustcean, here i meet up with a confused issue:
here is the code:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8267316ec3668cdd5ee9086d513d6afb

self.buf is a fat pointer to string which allocate at heap, so calling get_and_reset will causing self.buf point to a new string which also allocate at heap, and the old string will be moved to returned value, it seems very ok for me.

I can't understand why rust stop this? or is there any other code cases will lead to memory unsafe ?

There is a temporary move between the two statements. You can avoid this by using mem::replace or in your case where you take the value from the mutable reference and replace it with the default value of the type, mem::take. Here an example.

2 Likes

Thanks for your quick reply, i have found the wanted answer from another help topic:

wanted answer

so, in my posted code, if without "self.buf = String::new()", the self.buf will point to a invalid address, that is unsafe, so rust stop this code.

If you are interested you can read more about move semantics and ownership in the book:

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

2 Likes

Thank you for your patience reply, I will look into it. :slightly_smiling_face:

1 Like

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.