Recursively defining a type without using an Option

Currently, the following doesn’t work because the types cannot be instantiated without instances of themselves:

struct Outer {
    inner: Inner
}
struct Inner {
    outer: Box<Outer>
}
fn main() {
    let outer : Outer;
    outer = Outer { inner: Inner { outer: box outer };
}

However, this identical C program does work:

struct Inner {
    struct Outer * outer;
};
struct Outer {
    struct Inner inner;
};
int main() {
    struct Outer outer = { .inner = { .outer = &outer } };
    return 0;
}

So, is there any chance we could drop this error? Taking the address of an uninitialized variable is perfectly safe and the pattern of children pointing to parents is fairly common. While one could use an Option type, this would lead to run time checking of something that can (and should) be checked at compile time checking.

The programs are not identical. Box is an owning and a unique pointer, it simply cannot be in both places at once. You need *mut Outer to write the “identical” program in Rust.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.