rytone
rytone

Reputation: 165

Using a borrow as an associated trait type

This code works:

struct Test {
    val: String,
}

impl Test {
    fn mut_out(&mut self) -> &String {
        self.val = String::from("something");
        &self.val
    }
}

However, a more generic implementation does not work:

struct Test {
    val: String,
}

trait MutateOut {
    type Out;
    fn mut_out(&mut self) -> Self::Out;
}

impl MutateOut for Test {
    type Out = &String;

    fn mut_out(&mut self) -> Self::Out {
        self.val = String::from("something");
        &self.val
    }
}

The compiler cannot infer a lifetime for the string borrow:

error[E0106]: missing lifetime specifier
  --> src/main.rs:13:16
   |
11 |     type Out = &String;
   |                ^ expected lifetime parameter

I cannot figure out a way to explicitly state the lifetime of the borrow, as it depends on the function itself.

Upvotes: 2

Views: 113

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65087

Taking inspiration from the Deref trait, you can remove the reference from the associated type and instead just note in the trait that you want to return a reference to the associated type:

trait MutateOut {
    type Out;
    fn mut_out(&mut self) -> &Self::Out;
}

impl MutateOut for Test {
    type Out = String;

    fn mut_out(&mut self) -> &Self::Out {
        self.val = String::from("something");
        &self.val
    }
}

Here it is in the playground. Given that your function name was mut_out, if a mutable reference is what you were after, here is a playground example with that as well.

Upvotes: 6

Related Questions