// Define a simple enum for a linked list, demonstrating recursive types. // Without Box, this would be a compile-time error as the size of Node // would be infinite (recursive definition). Box allows Node to contain a // pointer to another Node, breaking the infinite size. enum List { Cons(i32, Box), // Cons: contains an integer and a box to the next List Nil, // Nil: represents the end of the list } use List::{Cons, Nil}; fn main() { // Create a linked list using Box for heap allocation let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); // Box allocates data on the heap and ensures single ownership. // When `list` goes out of scope, the memory for 1, 2, 3 and the List enums // will be deallocated automatically and safely. // Example of a simple heap-allocated integer let x = 5; let y = Box::new(x); // y is a Box pointing to 5 on the heap println!("x = {}", x); println!("*y = {}", *y); // Dereference y to get the value assert_eq!(x, 5); assert_eq!(*y, 5); // After `y` goes out of scope, the heap memory it pointed to is freed. }