Call a function from struct with own property as parameter

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.

Rust Playground.

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.

No, in this case you're not passing self.myStr under a reference, and are instead trying to move the value out of the struct. Changing it to self.my_func(self.myStr.clone()) would work.

If, instead you were trying to communicate this:

struct Test {
    my_str: String,
}

impl Test {
    fn my_func(&mut self, my_str: &String) { // Changes
        println!("{}", my_str);
    }
    fn called_func(&mut self) {
        self.my_func(&self.my_str);
    }
}

Then that won't work either, because self.my_func takes the entirety of self as a unique reference, and it doesn't check that you don't use self.my_str in my_func.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.