Rust 支持嵌套结构吗?

问题描述 投票:0回答:4

当我尝试在另一个结构体中声明一个结构体时:

struct Test {
    struct Foo {}
}

编译器抱怨:

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 `:`

我在这两个方向都找不到任何文档; Rust 是否支持嵌套结构?

struct rust
4个回答
62
投票

不,它们不受支持。您应该使用单独的结构声明和常规字段:

struct Foo {}

struct Test {
    foo: Foo,
}

1
投票

我找到了适合您请求的可选答案。 也许它可以帮助你: https://internals.rust-lang.org/t/nested-struct-declaration/13314/4

结构记录 592 将为您提供嵌套(没有隐私控制或命名)。

// From the RFC
struct RectangleTidy {
    dimensions: {
        width: u64,
        height: u64,
    },
    color: {
        red: u8,
        green: u8,
        blue: u8,
    },
}

以下是我的旧答案,请忽略。

使用稳定版本构建:1.65.0。 这是给您的一个例子。 铁锈游乐场

代码:

#[derive(Debug)]
struct Inner {
    i: i32,
}

#[derive(Debug)]
struct Outer {
    o: i32,
    inner: Inner,
}

pub fn test() {
    // add your code here
    let obj = Outer {
        o: 10,
        inner: Inner { i: 9 },
    };
    assert!(10i32 == obj.o);
    assert!(9i32 == obj.inner.i);
    println!("{}", obj.o);
    println!("{}", obj.inner.i);
    println!("{:?}", obj);
}
fn main() {
    test();
}

0
投票

Rust 不支持它们。

但是您可以自己编写一个模拟它们的 proc 宏。我,它变成了

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

进入

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

您没有明确这么说,但我怀疑您使用嵌套结构的目标不是更容易阅读的数据结构声明,而是命名空间? 实际上,您不能拥有一个名为

Test
的结构并以
Foo
的形式访问
Test::Foo
,但您可以为自己创建一个至少自动创建
mod test { Foo {} }
的 proc 宏。


0
投票

我最近发现structx可以满足我的大部分要求。

© www.soinside.com 2019 - 2024. All rights reserved.