我有一个铁 rust 发生器,它的参考值是&self
,但我得到的错误是let mut g = t.inner()
行上的borrow may still be in use when generator yields
,具体地说是参考值t
.
据我所知,编译器不能保证t
比生成器更长,尽管我已经添加了生命周期.有没有一种适当的方法来做到这一点,或者这只是一个生成器的警告?
#![feature(generators, generator_trait)]
use std::{ops::Generator, pin::Pin};
struct T(i32);
impl T {
// The nested generator and `&self` are important.
// Changing it to `self` and removing the lifetime fixes the error.
// Could elide the lifetime, but it's there for clarity.
fn inner<'a>(&'a self) -> impl Generator<(), Yield = i32, Return = ()> + Unpin + 'a {
move || {
// In the real example, the receiver type is `&mut self` so we need
// to pretend we have a reference to self in the generator.
// The real example is too large to include here.
let _ = self.0;
yield 0;
}
}
}
fn main() {
let t = T(10);
// Uncommenting this ref lets it compile for some reason?
// let t = &t;
let mut g = move || {
// On the other hand, this doesn't do anything other than moving the error
// let t = &t;
// The error is on the implicit reference to `t`
// More clear if it's changed to `let mut g = (&t).inner();`
let mut g = t.inner();
// Pretend to do something with the generator's results.
let _ = Pin::new(&mut g).resume(());
yield 0;
};
let _ = Pin::new(&mut g).resume(());
}