【发布时间】:2016-02-05 20:45:21
【问题描述】:
I'm working on a parser 有一堆不同的节点(现在约 6 种节点类型,稍后会更多),我有点迷失如何与节点项交互(所有节点都实现 Node 特征)所以我需要在任何地方使用Box<Node>。
ListNode 看起来像:
pub struct ListNode {
kind: NodeKind,
position: usize,
pub nodes: Vec<Box<Node>>
}
但我无法派生Clone,因为Node 没有实现它,并且每当我尝试获取例如测试中的那种节点时:
#[test]
fn test_plain_string() {
let mut parser = Parser::new("plain_string", "Hello world");
parser.parse();
assert_eq!(1, parser.root.nodes.len());
let ref node = parser.root.nodes[0];
let kind = node.get_kind();
assert_eq!(kind, NodeKind::Text);
}
我会遇到类似这样的借用和调整大小错误:
src/parser.rs:186:20: 186:24 error: cannot move out of borrowed content [E0507]
src/parser.rs:186 let kind = node.get_kind();
^~~~
src/parser.rs:186:20: 186:24 error: cannot move a value of type nodes::Node + 'static: the size of nodes::Node + 'static cannot be statically determined [E0161]
src/parser.rs:186 let kind = node.get_kind();
类似于这个测试is in the tests。
我应该如何访问 trait 对象或 Rust 中存在缺陷的这种方法?
是否可以将特征实现到特征(如 Debug)到特征,或者我是否为每个嵌入 Node 的结构手动实现 Debug?
【问题讨论】:
-
Node trait 的替代方案是使用枚举变体。这将解决尺寸问题。像这样:is.gd/IFSAi6
标签: rust