w3resource

Rust Program: Print Person fields

Rust Basic: Exercise-15 with Solution

Write a Rust program that creates an instance of the Person struct and prints its fields.

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("Zdeno Glenda"),
        age: 30,
    };

    // Print the fields of 'person1'
    println!("Name: {}", person1.name);
    println!("Age: {}", person1.age);
}

Output:

Name: Zdeno Glenda
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("Zdeno Glenda"): This line initializes the 'name' field of 'person1' with a "String" value "Zdeno Glenda". 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 Program: Define Person Struct.
Next: Rust Enum: Define Colors.

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.