'Are nested structs supported in Rust?

When I try to declare a struct inside of another struct:

struct Test {
    struct Foo {}
}

The compiler complains:

error: expected identifier, found keyword `struct`
 --> src/lib.rs:2:5
  |
2 |     struct Foo {}
  |     ^^^^^^ expected identifier, found keyword
help: you can escape reserved keywords to use them as identifiers
  |
2 |     r#struct Foo {}
  |     ^^^^^^^^

error: expected `:`, found `Foo`
 --> src/lib.rs:2:12
  |
2 |     struct Foo {}
  |            ^^^ expected `:`

I could not find any documentation in either direction; are nested structs even supported in Rust?



Solution 1:[1]

No, they are not supported. You should use separate struct declarations and regular fields:

struct Foo {}

struct Test {
    foo: Foo,
}

Solution 2:[2]

They are not supported by Rust.

But you can write yourself a proc macro that emulates them. I have, it turns

structstruck::strike!{
    struct Test {
        foo: struct {}
    }
}

into

struct Foo {}
struct Test {
    foo: Foo,
}

You haven't explicitly said so, but I suspect that your goal for using nested structs is not more easily readable data structure declarations, but namespacing? You can't actually have a struct named Test and access Foo as Test::Foo, but you could make yourself a proc macro that at least automatically creates a mod test { Foo {} }.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shepmaster
Solution 2 Caesar