Array as a struct field

前端 未结 2 1324
渐次进展
渐次进展 2021-02-07 01:15

I would like to create a non binary tree structure in Rust. Here is a try

struct TreeNode {
    tag : T,
    father : Weak>,
            


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 02:03

    If you don't know the size of the list in advance, you have two choices:

    1. &[T] which is just a reference to some piece of memory that you don't own
    2. Vec which is your own storage.

    The correct thing here is to use a Vec. Why? Because you want the children list (array of Rc) to be actually owned by the TreeNode. If you used a &[T], it means that someone else would be keeping the list, not the TreeNode. With some lifetime trickery, you could write some valid code but you would have to go very far to please the compiler because the borrowed reference would have to be valid at least as long as the TreeNode.

    Finally, a sentence in your question shows a misunderstanding:

    However, the structure is immutable and I do not need an overallocated Vec.

    You confuse mutability and ownership. Sure you can have an immutable Vec. It seems like you want to avoid allocating memory from the heap, but that's not possible, precisely because you don't know the size of the children list. Now if you're concerned with overallocating, you can fine-tune the vector storage with methods like with_capacity() and shrink_to_fit().

    A final note: if you actually know the size of the list because it is fixed at compile time, you just need to use a [T; n] where n is compile-time known. But that's not the same as [T].

提交回复
热议问题