filmov
tv
Rust: Storing Multiple Types with Enums and Vecs

Показать описание
In Rust, you can use Enums with Vecs to store different types of values in a single collection. Enums allow you to define custom types with multiple variants, while Vecs are growable, dynamic arrays. Combining them provides a powerful way to handle heterogeneous data efficiently. To achieve this, create an Enum with different variants, then declare a Vec with the Enum type. You can then push values of different types, matching the Enum variants, into the Vec and iterate over it, using pattern matching to handle each variant.
In this example, we define an Enum called DataType with three variants: Integer, Float, and Text. We then create a Vec named data with DataType Enum type and push values of different types, matching the Enum variants. Finally, we iterate over the Vec using a for loop, and apply pattern matching with match to handle each variant accordingly.
In this example, we define an Enum called DataType with three variants: Integer, Float, and Text. We then create a Vec named data with DataType Enum type and push values of different types, matching the Enum variants. Finally, we iterate over the Vec using a for loop, and apply pattern matching with match to handle each variant accordingly.