w3resource

Rust Program: Define result Enum

Rust Structs and Enums: Exercise-6 with Solution

Write a Rust program that creates an enum Result with variants representing success and failure states.

Sample Solution:

Rust Code:

// Define an enum named 'Result' with variants representing success and failure states
enum Result<T, E> {
    Success(T),
    Failure(E),
}

fn main() {
    // Example usage: Create variables representing success and failure states
    let success_result: Result<i32, &str> = Result::Success(42);
    let failure_result: Result<i32, &str> = Result::Failure("Error: Something went wrong");

    // Print the values of the variables representing success and failure states
    match success_result {
        Result::Success(value) => println!("Success: {}", value),
        Result::Failure(err) => println!("Failure: {}", err),
    }

    match failure_result {
        Result::Success(value) => println!("Success: {}", value),
        Result::Failure(err) => println!("Failure: {}", err),
    }
}

Output:

Success: 42
Failure: Error: Something went wrong

Explanation:

Here is a brief explanation of the above Rust code:

  • enum Result<T, E> { ... }: Defines an enum named "Result" with two generic type parameters 'T' and 'E'. It has two variants:
    • Success(T): Represents a success state with a value of type 'T'.
    • Failure(E): Represents a failure state with an error of type 'E'.
  • fn main() { ... }: This is the entry point of the program.
    • Inside main():
      • Variables 'success_result' and 'failure_result' are created, representing instances of "Result" enum with success and failure states, respectively.
      • Using pattern matching (match), the values of the variables are printed based on their variants. If it's a 'Success', the value is printed, and if it's a 'Failure', the error message is printed.

Rust Code Editor:

Previous: Rust Program: Define Student Struct & Print details.
Next: Rust Program: Calculate employee annual salary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.