我正在尝试Rust,但是我对泛型的数据类型一无所知。
为什么要执行以下操作:
trait IVertex {
}
struct GraphNode {
datum: Box<IVertex>,
edges: Vec<Rc<RefCell<GraphNode>>>,
}
struct Graph {
nodes: HashMap<i32, Rc<RefCell<GraphNode>>>,
}
但这不是:
trait IVertex {
}
struct GraphNode<T: IVertex> {
datum: Box<T>,
edges: Vec<Rc<RefCell<GraphNode<T>>>>,
}
struct Graph {
nodes: HashMap<i32, Rc<RefCell<GraphNode<IVertex>>>>,
}
第二个错误出现以下错误:
error[E0277]: the size for values of type `(dyn IVertex + 'static)` cannot be known at compilation time
--> src/main.rs:16:5
|
16 | nodes: HashMap<i32, Rc<RefCell<GraphNode<IVertex>>>>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn IVertex + 'static)`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `GraphNode`
当然,编译器无法知道正在实现IVertex
的数据类型的大小。但是,如果将值包装在Box
和RefCell
中,那还可以吗?因为指针大小总是相同?
之所以提出这样的设计,是因为我还具有以下特征:
trait ISpecializedVertex : IVertex {
}
我想拥有另一种数据结构,该结构能够保存对GraphNode
的引用,但只能包含对ISpecializedVertex
的引用。因此,我在GraphNode
中添加了通用名称。