w3resource

Rust Structs and Enums Exercises with Solutions and Explanations

Rust Structs and Enums Exercises [10 exercises with solution and Explanation]

[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]

1. Write a Rust program that defines a struct Rectangle with fields width and height. Write a function to calculate the area of a rectangle instance.

Click me to see the solution

2. Write a Rust program that creates an enum Direction with variants representing different directions (e.g., North, South, East, West).

Click me to see the solution

3. Write a Rust program that defines a struct Point with fields x and y. Now write a function to calculate the distance between two points.

Click me to see the solution

4. Write a Rust program that implements an enum Shape with variants representing different geometric shapes (e.g., Circle, Triangle, Square).

Click me to see the solution

5. Write a Rust program that defines a struct Student with fields like name, age, and email. The next step is to write a function that prints out the student's details.

Click me to see the solution

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

Click me to see the solution

7. Write a Rust program that defines a struct Employee with fields id, name, and salary. Now write a function to calculate an employee's annual salary.

Click me to see the solution

8. Write a Rust program that implements an enum Color with variants representing different colors (e.g., Red, Green, Blue).

Click me to see the solution

9. Write a Rust program that defines a struct Car with fields make, model, and year. Now write a function to print the details of a car.

Click me to see the solution

10. Write a Rust program that creates an enum Option with variants representing some and none states.

Click me to see the solution

Rust Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.