这个工作的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`
我能去掉重复的吗?
1条答案
按热度按时间ajsxfq5m1#
正如Jmb所指出的,您希望使用
upcast
而不是downcast
,之后您的代码可以编写为: