Rust Programming: Enum to Store Multiple Types

0

Enums are a powerful feature in Rust that allow you to represent a set of related values within a single data type. Enums can also be used to store multiple types, which can be useful in situations where you need to store a list of items of different types.

For example, consider the following enum:

Rust
enum SpreadsheetCell {
    Int(i32),
    Float(f64),
    Text(String),
}

This enum can be used to store values of three different types: integers, floating-point numbers, and strings.

We can then create a vector to hold values of this enum:

Rust
let row = vec![
    SpreadsheetCell::Int(3),
    SpreadsheetCell::Text(String::from("blue")),
    SpreadsheetCell::Float(10.12),
];

This vector can now hold values of all three types: integers, floating-point numbers, and strings.

Why use an enum to store multiple types?

There are a few reasons why you might want to use an enum to store multiple types:

  • Type safety: Enums help to ensure type safety by ensuring that only valid values can be stored in the vector.
  • Performance: Enums can improve the performance of your program by allowing the compiler to optimize the code.
  • Readability: Enums can make your code more readable and easier to understand by providing a clear way to represent different types of data.

Example

The following example shows how to use an enum to store multiple types and iterate over the vector:

Rust
enum SpreadsheetCell {
    Int(i32),
    Float(f64),
    Text(String),
}

fn main() {
    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];

    for cell in row {
        match cell {
            SpreadsheetCell::Int(value) => println!("Integer value: {}", value),
            SpreadsheetCell::Float(value) => println!("Floating-point value: {}", value),
            SpreadsheetCell::Text(value) => println!("String value: {}", value),
        }
    }
}

Output:

Integer value: 3
String value: blue
Floating-point value: 10.12

When not to use an enum to store multiple types

You should not use an enum to store multiple types if you do not know the exhaustive set of types that will be stored in the vector at runtime. In this case, you can use a trait object instead. Trait objects will be covered in Chapter 17 of the Rust book.

Post a Comment

0Comments
Post a Comment (0)