我怎样才能消除这个 rust 代码中的重复?

shstlldc  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(113)

这个工作的Rust代码重复本身有些:

fn append_column(tree: &TreeView, attribute: &str, id: i32) {
    let column = TreeViewColumn::new();
    match attribute {
        "text" => {
            let cell = CellRendererText::new();    
            TreeViewColumnExt::pack_start(&column, &cell, true);
            TreeViewColumnExt::add_attribute(&column, &cell, attribute, id);
        }
        "pixbuf" => {
            let cell = CellRendererPixbuf::new();
            TreeViewColumnExt::pack_start(&column, &cell, true);
            TreeViewColumnExt::add_attribute(&column, &cell, attribute, id);
        }
        _ => { panic!("Unexpected attribute") }
    }
    tree.append_column(&column);
}

我尝试使用downcast()来简化它,如下所示:

fn append_column(tree: &TreeView, attribute: &str, id: i32) {
    let column = TreeViewColumn::new();
    let cell : CellRenderer;
    match attribute {
        "text" => { cell = CellRendererText::new().downcast::<CellRenderer>().unwrap() }
        "pixbuf" => { cell = CellRendererPixbuf::new().downcast::<CellRenderer>().unwrap() }
        _ => { panic!("Unexpected attribute") }
    }
    TreeViewColumnExt::pack_start(&column, &cell, true);
    TreeViewColumnExt::add_attribute(&column, &cell, attribute, id);
    tree.append_column(&column);
}

但我得到了以下错误:

error[E0277]: the trait bound `CellRenderer: IsA<CellRendererText>` is not satisfied
   --> src/main.rs:23:52
    |
23  |         "text" => { cell = CellRendererText::new().downcast::<CellRenderer>().unwrap() }
    |                                                    ^^^^^^^^ the trait `IsA<CellRendererText>` is not implemented for `CellRenderer`

我能去掉重复的吗?

ajsxfq5m

ajsxfq5m1#

正如Jmb所指出的,您希望使用upcast而不是downcast,之后您的代码可以编写为:

use gtk::{
    prelude::*, CellRenderer, CellRendererPixbuf, CellRendererText, TreeView, TreeViewColumn,
};

fn append_column(tree: &TreeView, attribute: &str, id: i32) {
    let column = TreeViewColumn::new();
    let cell: CellRenderer = match attribute {
        "text" => CellRendererText::new().upcast(),
        "pixbuf" => CellRendererPixbuf::new().upcast(),
        _ => panic!("Unexpected attribute"),

    };
    TreeViewColumnExt::pack_start(&column, &cell, true);
    TreeViewColumnExt::add_attribute(&column, &cell, attribute, id);
    tree.append_column(&column);
}

相关问题