使用借用作为相关特征类型

时间:2017-09-12 00:54:26

标签: rust

此代码有效:

struct Test {
    val: String,
}

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

但是,更通用的实现不起作用:

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
    }
}

编译器无法推断字符串借用的生命周期:

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

我无法想出一种明确说明借用生命周期的方法,因为它取决于函数本身。

1 个答案:

答案 0 :(得分:6)

Deref trait中获取灵感,您可以从相关类型中删除引用,而只是在特征中注意您要返回对相关类型的引用:

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
    }
}

这里it is in the playground。鉴于您的函数名称为mut_out,如果您使用的是here is a playground example with that as well,那么可变引用就是。{/ p>