【发布时间】:2015-05-15 15:08:55
【问题描述】:
我想在 Rust 中创建一个非二叉树结构。这是一个尝试
struct TreeNode<T> {
tag : T,
father : Weak<TreeNode<T>>,
childrenlists : [Rc<TreeNode<T>>]
}
很遗憾,这无法编译。
main.rs:4:1: 8:2 error: the trait `core::marker::Sized` is not implemented for the type `[alloc::rc::Rc<TreeNode<T>>]` [E0277]
main.rs:4 struct TreeNode<T> {
main.rs:5 tag : T,
main.rs:6 father : Weak<TreeNode<T>>,
main.rs:7 childrenlist : [Rc<TreeNode<T>>]
main.rs:8 }
main.rs:4:1: 8:2 note: `[alloc::rc::Rc<TreeNode<T>>]` does not have a constant size known at compile-time
main.rs:4 struct TreeNode<T> {
main.rs:5 tag : T,
main.rs:6 father : Weak<TreeNode<T>>,
main.rs:7 childrenlist : [Rc<TreeNode<T>>]
main.rs:8 }
error: aborting due to previous error
如果我们用Vec 替换一个数组,代码就会编译。但是,该结构是不可变的,我不需要过度分配的 Vec。
我听说在编译时可以有一个大小未知的结构字段,只要它是唯一的。我们该怎么做?
【问题讨论】:
-
我认为要求是“最后一个”,但无论如何这里也是如此。我找到了reddit.com/r/rust/comments/357ji5/…
-
在 Rust 中,数组 有一个固定的大小,在编译时就知道了。因此,您不需要“数组”。
&[T]通常被称为slice,我不知道[T]的发音。 -
@Shepmaster 我猜那将是“未调整大小的数组”。
标签: rust