繁体   English   中英

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

[英]Using a borrow as an associated trait type

此代码有效:

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

我无法找出一种明确声明借用期限的方法,因为它取决于函数本身。

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

是在操场上 假设您的函数名是mut_out ,那么如果要使用可变引用,那么这里也是一个操场示例

暂无
暂无

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

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