Rust Program: Define Person Struct
Rust Basic: Exercise-14 with Solution
Write a Rust program that defines a struct Person with fields like name and age.
Sample Solution:
Rust Code:
// Define a struct named 'Person' with fields 'name' and 'age'
struct Person {
name: String,
age: u32,
}
fn main() {
// Create a new instance of 'Person' struct
let person1 = Person {
// Assign values to 'name' and 'age' fields
name: String::from("Salih Yejide"),
age: 30,
};
// Access and print the fields of 'person1'
println!("Name: {}", person1.name);
println!("Age: {}", person1.age);
}
Output:
Name: Salih Yejide Age: 30
Explanation:
Here's a brief explanation of the above Rust code:
- struct Person { ... }: This line defines a new struct named "Person" with two fields: 'name' of type 'String' and 'age' of type 'u32'.
- let person1 = Person { ... };: This line creates a new instance of the "Person" struct named 'person1' and initializes its fields with values.
- name: String::from("Salih Yejide"): This line initializes the 'name' field of 'person1' with a String value "Salih Yejide". We use String::from to create a new "String" instance from a string literal.
- age: 30: This line initializes the 'age' field of 'person1' with an integer value 30.
- println!("Name: {}", person1.name);: This line prints the value of the 'name' field of person1.
- println!("Age: {}", person1.age);: This line prints the value of the 'age' field of person1.
Rust Code Editor:
Previous: Rust Function: Find smallest string.
Next: Rust Program: Print Person fields.
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-basic-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics