相关疑难解决方法(0)

我可以用特征对象键入内省然后向下转换吗?

我有一个集合Trait,一个迭代它并执行某些操作的函数,然后我想检查实现者类型,如果它是类型Foo然后向下转换它并调用一些Foo方法.

基本上,类似于Go的类型切换界面转换.

搜索我发现任何特征,但它只能在'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)

rust

10
推荐指数
1
解决办法
2303
查看次数

Downcasting和Box <Any>

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中的编码水平我不太了解,但也许有人可以帮助我更好地掌握上述任务中涉及的概念.

downcast rust

6
推荐指数
1
解决办法
3872
查看次数

匹配表达式(模式匹配)如何不需要运行时类型信息来工作?

match该表达式是如何在高层次上实现的?编译器在幕后发生了什么才能知道如何将某些代码片段定向到一个分支与另一个分支,并在编译时弄清楚它?我不明白如果不存储运行时使用的类型信息,这怎么可能。

\n

像这个例子:

\n
fn 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)

compiler-construction pattern-matching rust

0
推荐指数
2
解决办法
1634
查看次数