Rust Program: Car Details
Rust Structs and Enums: Exercise-9 with Solution
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.
Sample Solution:
Rust Code:
// Define a struct named 'Car' with fields representing make, model, and year
struct Car {
make: String,
model: String,
year: u32,
}
// Function to print the details of a car
fn print_car_details(car: &Car) {
println!("Car Details:");
println!("Make: {}", car.make);
println!("Model: {}", car.model);
println!("Year: {}", car.year);
}
fn main() {
// Create an instance of the Car struct
let my_car = Car {
make: String::from("Toyota"),
model: String::from("Camry"),
year: 2020,
};
// Print the details of the car
print_car_details(&my_car);
}
Output:
Car Details: Make: Toyota Model: Camry Year: 2020
Explanation:
The above Rust program defines a 'Car' struct with fields for the make, model, and year of the car. It also defines a function 'print_car_details' that takes a reference to a 'Car' instance and prints out its details. In the 'main' function, an instance of the 'Car' struct is created and its details are printed using the 'print_car_details' function.
Rust Code Editor:
Previous: Rust Program: Enum Colors.
Next: Rust Program: Option Enum.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-structs-and-enums-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics