在 Rust 中将盒装特征转换为可变特征引用 [英] Convert boxed trait to mutable trait reference in Rust
问题描述
我在 Rust 中的动态调度指针类型方面遇到了一些问题.我想将 Box
类型的值转换为 &mut MyTrait
以传递给函数.例如,我试过:
I am having some trouble with the dynamic dispatch pointer types in Rust. I want to convert a value of type Box<MyTrait>
to &mut MyTrait
to pass to a function. 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());
}
失败并出现以下错误:
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
奇怪的是,这适用于 &MyTrait
但不适用于 &mut MyTrait
.有什么办法可以让这种转换在可变情况下工作吗?
Strangely enough, this works for &MyTrait
but not for &mut MyTrait
. Is there any way I can get this conversion to work in the mutable case?
推荐答案
我认为您遇到了当前编译器生命周期处理的限制.borrow_mut
作为一个函数,对生命周期的要求比必要的要严格.
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.
相反,您可以通过首先取消引用框来对框的内部进行可变借用,如下所示:
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);
}
这篇关于在 Rust 中将盒装特征转换为可变特征引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!