Skip to content

Instantly share code, notes, and snippets.

@dinfuehr
Created January 26, 2015 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinfuehr/6e07ff2b3c0315dab7d6 to your computer and use it in GitHub Desktop.
Save dinfuehr/6e07ff2b3c0315dab7d6 to your computer and use it in GitHub Desktop.
Rust: cannot move out of borrowed content
struct Foo {
value: String
}
impl Foo {
fn test(&mut self) -> String {
let old = self.value;
self.value = "new".to_string();
old
}
}
fn main() {
let mut foo = Foo { value: "old".to_string() };
assert_eq!("old", foo.test());
println!("foo = {}", foo.value);
}
@dinfuehr
Copy link
Author

Error is thrown at line 7. How can I replace the value in the struct, but also retain the old value?

@dinfuehr
Copy link
Author

Can be solved with mem::replace(&mut self.value, "new".to_string()). see documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment