我遇到了一个问题,该特征可以返回对以self
为单位的数据的引用. 这是一个最小的例子:
trait A<T> {
fn emit_symbol(&mut self) -> T;
}
fn via_ans<'a>(emitter: &'a mut impl A<char>) -> String {
let mut rval = String::new();
for _ in 0..30 {
let ch = emitter.emit_symbol();
rval.push(ch)
}
rval
}
struct Hippo<T> {
things: Vec<T>,
}
impl<T> A<&T> for Hippo<T> {
fn emit_symbol(&mut self) -> &T {
&self.things[2]
}
}
给出错误
error: `impl` item signature doesn't match `trait` item signature
--> src/b.rs:19:5
|
2 | fn emit_symbol(&mut self) -> T;
| ------------------------------- expected `fn(&'1 mut b::Hippo<T>) -> &'2 T`
...
19 | fn emit_symbol(&mut self) -> &T {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&'1 mut b::Hippo<T>) -> &'1 T`
|
= note: expected signature `fn(&'1 mut b::Hippo<T>) -> &'2 T`
found signature `fn(&'1 mut b::Hippo<T>) -> &'1 T`
help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait`
--> src/b.rs:2:34
|
2 | fn emit_symbol(&mut self) -> T;
| ^ consider borrowing this type parameter in the trait
如果我将生命周期添加到trait中为&'s self
,那么实现就会工作,但我在使用trait方法的循环中遇到了新错误.
trait A<'s, T> {
fn emit_symbol(&'s mut self) -> T;
}
fn via_ans<'a: 'b, 'b>(emitter: &'a mut impl A<'b, char>) -> String {
let mut rval = String::new();
for _ in 0..30 {
let ch = emitter.emit_symbol();
rval.push(ch)
}
rval
}
struct Hippo<T> {
things: Vec<T>,
}
impl<'s, T> A<'s, &'s T> for Hippo<T> {
fn emit_symbol(&'s mut self) -> &'s T {
&self.things[2]
}
}
给出错误
error[E0499]: cannot borrow `*emitter` as mutable more than once at a time
--> src/main.rs:10:18
|
7 | fn via_ans<'a: 'b, 'b>(emitter: &'a mut impl A<'b, char>) -> String {
| -- lifetime `'b` defined here
...
10 | let ch = emitter.emit_symbol();
| ^^^^^^^--------------
| |
| `*emitter` was mutably borrowed here in the previous iteration of the loop
| argument requires that `*emitter` is borrowed for `'b`
这是Rust的borrow 判断器的缺点,还是还有其他问题?
如何调整此特征以在我的应用程序中工作?