我有一个集合Trait,一个迭代它并执行某些操作的函数,然后我想检查实现者类型,如果它是类型Foo然后向下转换它并调用一些Foo方法.
搜索我发现任何特征,但它只能在'static类型上实现.
为了帮助展示我想要的东西:
let vec: Vec<Box<Trait>> = //
for e in vec.iter() {
e.trait_method();
// if typeof e == Foo {
// let f = e as Foo;
// f.foo_method();
//}
}
Run Code Online (Sandbox Code Playgroud) pub struct WidgetWrap {
// ...
widget: RefCell<Box<Any>>,
}
Run Code Online (Sandbox Code Playgroud)
在某些时候,我想投Box<Any>给Box<WidgetTrait>
let mut cell = widget.borrow_mut();
let w = cell.downcast_mut::<Box<WidgetTrait>>();
Run Code Online (Sandbox Code Playgroud)
这给了我这样的错误:
error: instantiating a type parameter with an incompatible type
`Box<WidgetTrait>`, which does not fulfill `'static` [E0144]
Run Code Online (Sandbox Code Playgroud)
这究竟意味着什么?
我看过如何解决:值可能包含引用; 添加`'static`绑定到`T`并尝试添加+ 'static到处.
pub struct WidgetWrap {
// ...
widget: RefCell<Box<Any + 'static>>,
}
let mut cell = widget.borrow_mut();
let w = cell.downcast_mut::<Box<WidgetTrait + 'static>>();
Run Code Online (Sandbox Code Playgroud)
它修复了编译错误,但是当我尝试打开如下所示的downcasrap框时失败.是的,盒子的内容是一个实现的对象WidgetTrait.
显然,我在Rust中的编码水平我不太了解,但也许有人可以帮助我更好地掌握上述任务中涉及的概念.
match该表达式是如何在高层次上实现的?编译器在幕后发生了什么才能知道如何将某些代码片段定向到一个分支与另一个分支,并在编译时弄清楚它?我不明白如果不存储运行时使用的类型信息,这怎么可能。
像这个例子:
\nfn tree_weight_v1(t: BinaryTree) -> i32 {\n match t {\n BinaryTree::Leaf(payload) => payload,\n BinaryTree::Node(left, payload, right) => {\n tree_weight_v1(*left) + payload + tree_weight_v1(*right)\n }\n }\n}\n\n/// Returns tree that Looks like:\n///\n/// +----(4)---+\n/// | |\n/// +-(2)-+ [5]\n/// | | \n/// [1] [3]\n///\nfn sample_tree() -> BinaryTree {\n let l1 = Box::new(BinaryTree::Leaf(1));\n let l3 = Box::new(BinaryTree::Leaf(3));\n let n2 = Box::new(BinaryTree::Node(l1, 2, l3));\n let l5 = Box::new(BinaryTree::Leaf(5));\n\n BinaryTree::Node(n2, 4, l5)\n}\n\n#[test]\nfn tree_demo_1() {\n let tree = sample_tree();\n assert_eq!(tree_weight_v1(tree), (1 …Run Code Online (Sandbox Code Playgroud)