简体   繁体   English

使用借位作为关联的特征类型

[英]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. 我无法找出一种明确声明借用期限的方法,因为它取决于函数本身。

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: Deref特征中获取灵感,您可以从关联的类型中删除引用,而只是在特征中注明要返回对关联类型的引用:

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 . 假设您的函数名是mut_out ,那么如果要使用可变引用,那么这里也是一个操场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM