Why are recursive data structures prohibited in Rust and how to create them correctly?
Hello, colleagues! I started learning Rust and encountered an unclear error. I want to make a simple linked list, like in C or Python:
```rust
struct Node {
value: i32,
next: Node, // error: recursive type `Node` has infinite size
}
```
The compiler says: "recursive type `Node` has infinite size". I understand that Rust is strict about type sizes, but why is this a problem? In C, I can do `struct Node { int value; struct Node* next; }` — there's a pointer, and it works. In Python, you can even store an object inside itself.
Why does Rust prohibit such recursion? And how do you then make lists, trees, and other recursive structures? I've heard about `Box`, but I don't understand why it solves the problem. Please explain in simple terms with examples. Thanks in advance!
<<>>
By
No answers yet.
Log in to leave an answer