Rust Program: Define Student Struct & Print details
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.
Sample Solution:
Rust Code:
// Define a struct named 'Student' with fields: name, age, and email
struct Student {
name: String,
age: u32,
email: String,
}
// Define a function to print the student's details
fn print_student_details(student: &Student) {
println!("Name: {}", student.name);
println!("Age: {}", student.age);
println!("Email: {}", student.email);
}
fn main() {
// Create a student instance
let student = Student {
name: String::from("Bonolo Itxaro"),
age: 20,
email: String::from("[email protected]"),
};
// Print the student's details using the function
print_student_details(&student);
}
Output:
Name: Bonolo Itxaro Age: 20 Email: [email protected]
Explanation:
Here is a brief explanation of the above Rust code:
- struct Student { ... }: Defines a struct named "Student" with fields 'name', 'age', and 'email'. Each field has its respective data type.
- fn print_student_details(student: &Student) { ... }: Defines a function named "print_student_details()" that takes a reference to a "Student" instance as a parameter. Inside the function, it prints out the student's details using println! macro.
- fn main() { ... }: This is the entry point of the program.
- Inside main():
- A "Student" instance named 'student' is created with sample details.
- The "print_student_details()" function is called with a reference to the 'student' instance to print out its details.
Rust Code Editor:
Previous: Rust Program: Implement Enum for Geometric shapes.
Next: Rust Program: Define result Enum.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics