Are nested structs supported in Rust?

StructRust

Struct Problem Overview


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?

Struct Solutions


Solution 1 - Struct

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

struct Foo {}

struct Test {
    foo: Foo,
}

Solution 2 - Struct

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 {} }.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionabergmeierView Question on Stackoverflow
Solution 1 - StructVladimir MatveevView Answer on Stackoverflow
Solution 2 - StructCaesarView Answer on Stackoverflow