Why are recursive struct types illegal in Rust?

后端 未结 2 397
别那么骄傲
别那么骄傲 2020-12-01 04:10

I\'m trying out random things to deepen my understanding of Rust. I just ran into the following error with this code:

struct Person {
    mother: Option<         


        
2条回答
  •  [愿得一人]
    2020-12-01 04:43

    Data inside structs and enums (and tuples) is stored directly inline inside the memory of the struct value. Given a struct like

    struct Recursive {
        x: u8,
        y: Option
    }
    

    let's compute the size: size_of::(). Clearly it has 1 byte from the x field, and then the Option has size 1 (for the discriminant) + size_of::() (for the contained data), so, in summary, the size is the sum:

    size_of::() == 2 + size_of::()
    

    That is, the size would have to be infinite.

    Another way to look at it is just expanding Recursive repeatedly (as tuples, for clarity):

    Recursive ==
    (u8, Option) ==
    (u8, Option<(u8, Option)>) ==
    (u8, Option<(u8, Option<(u8, Option)>)>) ==
    ...
    

    and all of this is stored inline in a single chunk of memory.

    A Box is a pointer, i.e. it has a fixed size, so (u8, Option>) is 1 + 8 bytes. (One way to regard Box is that it's a normal T with the guarantee that it has a fixed size.)

提交回复
热议问题