I have a struct with one property and a few functions. One of those functions has a string parameter. That parameter needs to get the value of the property of that same struct.
But this seems to give some issues.
Code:
struct Test {
myStr: String,
}
impl Test {
fn my_func(&mut self, myStr: String) {
println!("{}", myStr);
}
fn called_func(&mut self) {
self.my_func(self.myStr);
}
}
fn main() {
let mut t : Test = Test{myStr: "String".to_string()};
t.called_func();
}
Error:
Compiling playground v0.0.1 (/playground)
error[E0507]: cannot move out of `self.myStr` which is behind a mutable reference
--> src/main.rs:11:22
|
11 | self.my_func(self.myStr);
| ^^^^^^^^^^ move occurs because `self.myStr` has type `std::string::String`, which does not implement the `Copy` trait
error[E0505]: cannot move out of `self.myStr` because it is borrowed
--> src/main.rs:11:22
|
11 | self.my_func(self.myStr);
| ---- ------- ^^^^^^^^^^ move out of `self.myStr` occurs here
| | |
| | borrow later used by call
| borrow of `*self` occurs here
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0505, E0507.
For more information about an error, try `rustc --explain E0505`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
I think this is because self.myStr
needs to live as long as self
. But because self
is mutable the property self.myStr
is also mutable and this gives an error because I borrow out self.myStr
as a parameter to a function of Test which gets destroyed so self.myStr
also gets destroyed? But that isn't allowed because it needs to live as long as ```self````?
Any help would be appreciated.