error[E0072]: recursive type `Coach` has infinite size
--> src/main.rs:4:5
|
4 | pub struct Coach {
| ^^^^^^^^^^^^^^^^ recursive type has infinite size
...
7 | team: Team
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Coach` representable
|
7 | team: 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: Coach
| ----- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Team` representable
|
14 | coach: Box<Coach>
| ++++ +
For more information about this error, try `rustc --explain E0072`.
Coming from Go where something like this is easily possible, what is Rust idiomatic code?
Very small runtime cost of an indirection (both Rc and Box and a counter (for Rc).
Don't. Absolutely do not only use lifetimes. If you observe the Rust ecosystem you'll learn when lifetime are appropriate when they are not (mostly only appropriate for "view structs").
You're just bumping against a fundamental issue with the borrowing model and linked lists. It's quite hard to do correctly in Rust, it's hard to do correctly in other languages too, but rust will check that you do it somewhat correctly.
Don't put references in structs. Reference in a struct means the struct is not storing its data, and you will be unable to build the graph. The correct type for storing things by reference in structs is Box (or Rc/Arc or something else owning, not &).
Given the way the two structs refer to each other, you may eventually run into circular reference problems. One way around this is to have a Vec of coaches, a Vec of teams, and store indexes to each other.
You have to use new_cyclic since the team on Coach isn't optional, and neither is the coach field on Team.
This setup won't work correctly if you try and use a Coach without keeping the Rc<Team> around though, since Weak's purpose is to not increase the reference count.