简体   繁体   English

将盒装特征转换为Rust中的可变特征引用

[英]Convert boxed trait to mutable trait reference in Rust

I am having some trouble with the dynamic dispatch pointer types in Rust. 我在Rust中使用动态调度指针类型时遇到了一些问题。 I want to convert a value of type Box<MyTrait> to &mut MyTrait to pass to a function. 我想将Box<MyTrait>类型的值转换为&mut MyTrait以传递给函数。 For example, I tried: 例如,我尝试过:

use std::borrow::BorrowMut;

trait MyTrait {
    fn say_hi(&mut self);
}

struct MyStruct { }

impl MyTrait for MyStruct {
    fn say_hi(&mut self) {
        println!("hi");
    }
}

fn invoke_from_ref(value: &mut MyTrait) {
    value.say_hi();
}

fn main() {
    let mut boxed_trait: Box<MyTrait> = Box::new(MyStruct {});
    invoke_from_ref(boxed_trait.borrow_mut());
}

This fails with the following error: 此操作失败,并显示以下错误:

error: `boxed_trait` does not live long enough
  --> <anon>:22:5
   |
21 |         invoke_from_ref(boxed_trait.borrow_mut());
   |                         ----------- borrow occurs here
22 |     }
   |     ^ `boxed_trait` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

Strangely enough, this works for &MyTrait but not for &mut MyTrait . 奇怪的是,这适用于&MyTrait但不适用于&mut MyTrait Is there any way I can get this conversion to work in the mutable case? 有什么办法可以让这个转换在可变的情况下工作吗?

I think you're running into a limitation of the current compiler's lifetime handling. 我认为你遇到了当前编译器生命周期处理的限制。 borrow_mut , being a function, imposes stricter lifetime requirements than necessary. borrow_mut ,作为一个函数,强加了比必要更严格的生命周期要求。

Instead, you can take a mutable borrow to the box's interior by first dereferencing the box, like this: 相反,您可以通过首先解除引用框来对盒子的内部进行可变借用,如下所示:

fn main() {
    let mut boxed_trait: Box<MyTrait> = Box::new(MyStruct {});
    invoke_from_ref(&mut *boxed_trait);
}

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

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