Rust Programming: Enum Values

0

An enum value is a value that can be one of a set of possible variants. Enums are a powerful tool in Rust for representing data that can have different forms. For example, the following enum represents the possible results of a coin flip:

enum CoinFlip {

    Heads,

    Tails,

}

The enum has two variants, `Heads` and `Tails`, which represent the two possible results of a coin flip. We can create an instance of the enum like this:

let coin_flip = CoinFlip::Heads;

We can then use the `coin_flip` variable to represent the result of the coin flip.

Enums can also be used to represent more complex data. For example, the following enum represents the possible results of a HTTP request:

enum HttpResponse {

    Success(String),

    Failure(String),

}

The enum has two variants, `Success` and `Failure`, which represent the two possible results of a HTTP request. The `Success` variant contains the body of the HTTP response, and the `Failure` variant contains an error message. We can create an instance of the enum like this:

let http_response = HttpResponse::Success(String::from("OK"));

We can then use the `http_response` variable to represent the result of the HTTP request.

Post a Comment

0Comments
Post a Comment (0)