rust 如何使用嵌套结构体?[duplicate]

py49o6xq  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(208)

此问题在此处已有答案

Why are recursive struct types illegal in Rust?(3个答案)
23天前关闭。
截至23天前,机构群体正在审查是否重新讨论此问题。
我是Rust的新手,这是我第一次写这样的代码:
PLAYGROUND HERE


# [tokio::main]

async fn main() {
    #[derive(Default, Clone)]
    pub struct Coach {
        id: Option<i64>,
        name: String,
        team: Option<Team>
    }

    #[derive(Default, Clone)]
    pub struct Team {
        id: Option<i64>,
        name: String,
        coach: Option<Coach>
    }
}

错误为:

error[E0072]: recursive type `Coach` has infinite size
 --> src/main.rs:4:5
  |
4 |     pub struct Coach {
  |     ^^^^^^^^^^^^^^^^ recursive type has infinite size
...
7 |         team: Option<Team>
  |               ------------ recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Coach` representable
  |
7 |         team: Option<Box<Team>>
  |                      ++++    +

error[E0072]: recursive type `Team` has infinite size
  --> src/main.rs:11:5
   |
11 |     pub struct Team {
   |     ^^^^^^^^^^^^^^^ recursive type has infinite size
...
14 |         coach: Option<Coach>
   |                ------------- recursive without indirection
   |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Team` representable
   |
14 |         coach: Option<Box<Coach>>
   |                       ++++     +

For more information about this error, try `rustc --explain E0072`.

在Go语言中,这样的代码很容易实现,那么Rust的惯用代码是什么?

oug3syen

oug3syen1#

添加Box,因为它是“指针”


# [tokio::main]

async fn main() {
    #[derive(Default, Clone)]
    pub struct Coach {
        id: Option<i64>,
        name: String,
        team: Option<Box<Team>>
    }

    #[derive(Default, Clone)]
    pub struct Team {
        id: Option<i64>,
        name: String,
        coach: Option<Box<Coach>>
    }
}

您可以参考https://rust-unofficial.github.io/too-many-lists/first-layout.html?highlight=box#basic-data-layout

相关问题