Array as a struct field

前端 未结 2 1326
渐次进展
渐次进展 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:04

    Rust doesn't have the concept of a variable-length (stack) array, which you seem to be trying to use here.

    Rust has a couple different array-ish types.

    • Vec ("vector"): Dynamically sized; dynamically allocated on the heap. This is probably what you want to use. Initialize it with Vec::with_capacity(foo) to avoid overallocation (this creates an empty vector with the given capacity).
    • [T; n] ("array"): Statically sized; lives on the stack. You need to know the size at compile time, so this won't work for you (unless I've misanalysed your situation).
    • [T] ("slice"): Unsized; usually used from &[T]. This is a view into a contiguous set of Ts in memory somewhere. You can get it by taking a reference to an array, or a vector (called "taking a slice of an array/vector"), or even taking a view into a subset of the array/vector. Being unsized, [T] can't be used directly as a variable (it can be used as a member of an unsized struct), but you can view it from behind a pointer. Pointers referring to [T] are fat ; i.e. they have an extra field for the length. &[T] would be useful if you want to store a reference to an existing array; but I don't think that's what you want to do here.

提交回复
热议问题