Rust 使用特征作为类型参数时借用检查器失败

Rust 使用特征作为类型参数时借用检查器失败,rust,borrow-checker,Rust,Borrow Checker,在结构中将traits用作类型参数时,借用检查器有问题: trait Trait {} struct FooBar; impl Trait for FooBar{} struct Observer<Arg> { action: Box<Fn(Arg) + Send>, // Other fields } impl <Arg> Observer<Arg> { fn new(action: Box<Fn(Arg) +

在结构中将traits用作类型参数时,借用检查器有问题:

trait Trait {}

struct FooBar;
impl Trait for FooBar{}

struct Observer<Arg> {
    action: Box<Fn(Arg) + Send>,
    // Other fields
}

impl <Arg> Observer<Arg> {
    fn new(action: Box<Fn(Arg) + Send>) -> Observer<Arg> {
        Observer{action: action}
    }

    fn execute(&self, arg: Arg) {
        (*self.action)(arg);
    }
}

fn test() {
    let mut foobar = FooBar;
    {
        let mut observer = Observer::new(Box::new(|&: param: &mut Trait| {
            // do something with param here
        }));
        observer.execute(&mut foobar);   // First borrow passes ...
        observer.execute(&mut foobar);   // This fails as "foobar" is already borrowed
    }   // The previous borrow ends here (lifetime of "observer")
}
然而,下面的例子是有效的:

trait Trait {}

struct FooBar;
impl Trait for FooBar{}

struct Observer {
    action: Box<Fn(&mut Trait) + Send>,
    // Other fields
}

impl Observer {
    fn new(action: Box<Fn(&mut Trait) + Send>) -> Observer {
        Observer{action: action}
    }

    fn execute(&self, arg: &mut Trait) {
        (*self.action)(arg);
    }
}

fn test() {
    let mut foobar = FooBar;
    {
        let mut observer = Observer::new(Box::new(|&: param: &mut Trait| {
            // do something with param here
        }));
        observer.execute(&mut foobar);
        observer.execute(&mut foobar);
    }
}
编辑1:精确化用例

编辑2:正如下面的答案所解释的,问题在于借用检查器强制
观察者的生存期与
&mut Type
相同,因此实际上问题与我们使用特征作为类型参数这一事实无关(它与实际结构的生存期相同)。
因此,在我的例子中,我可以通过如下定义
Observer
找到解决方法:

struct Observer<Arg> {
    action: Box<Fn(&mut Arg) + Send>,
}
struct-Observer{
行动:盒子,
}

因此,类型参数Arg本身不是引用,但这使代码不那么通用。有谁有更好的解决方案吗?

这里的问题是借用检查器正在强制
&mut Trait
引用的生存期与整个
通用结构相同。我相信这是因为引用是结构本身的类型参数

由于您的结构没有存储引用的字段(如果您需要在原始代码中执行此操作,请更新您的问题),因此您可以将类型参数移动到方法本身,而不是结构:

trait Trait{}

struct FooBar;
impl Trait for FooBar{}

struct GenericStruct;

impl GenericStruct {
    fn bar<T>(&self, _: T) {}
}

fn main() {
    let mut foobar = FooBar;

    {
        let foo = GenericStruct;
        foo.bar(&mut foobar);
        foo.bar(&mut foobar);
    }
}
trait{}
结构FooBar;
FooBar{}的impl特征
结构泛型结构;
impl通用结构{
fn bar(&self,{uu:T}
}
fn main(){
让mut foobar=foobar;
{
设foo=GenericStruct;
foo.bar(和mut foobar);
foo.bar(和mut foobar);
}
}
这将使借用只在调用
foo.bar()
时持续

struct Observer<Arg> {
    action: Box<Fn(&mut Arg) + Send>,
}
trait Trait{}

struct FooBar;
impl Trait for FooBar{}

struct GenericStruct;

impl GenericStruct {
    fn bar<T>(&self, _: T) {}
}

fn main() {
    let mut foobar = FooBar;

    {
        let foo = GenericStruct;
        foo.bar(&mut foobar);
        foo.bar(&mut foobar);
    }
}