此代码有效:
struct Test {
val: String,
}
impl Test {
fn mut_out(&mut self) -> &String {
self.val = String::from("something");
&self.val
}
}
Run Code Online (Sandbox Code Playgroud)
但是,更通用的实现不起作用:
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
}
}
Run Code Online (Sandbox Code Playgroud)
编译器无法推断字符串借用的生命周期:
error[E0106]: missing lifetime specifier
--> src/main.rs:13:16
|
11 | type Out = &String;
| ^ expected lifetime parameter
Run Code Online (Sandbox Code Playgroud)
我无法想出一种明确说明借用生命周期的方法,因为它取决于函数本身.
从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
}
}
Run Code Online (Sandbox Code Playgroud)
这是在操场上.鉴于您的函数名称是mut_out,如果您使用的是可变引用,那么这里也是一个操场示例.