Implementing a Default Trait in Rust
Rust's Default trait provides a convenient way to create default values for types. This challenge asks you to implement the Default trait for a custom struct, ensuring that instances can be easily created with sensible default values when no specific initialization is provided. This is a fundamental concept for simplifying object creation and providing fallback behavior.
Problem Description
You are tasked with defining a struct called Person with fields name (String) and age (u32). You must implement the Default trait for the Person struct. The default name should be "Unknown", and the default age should be 0. Your implementation should allow you to create a Person instance without providing any arguments, resulting in a Person with the specified default values.
Key Requirements:
- Define a struct
Personwithname: Stringandage: u32fields. - Implement the
Defaulttrait for thePersonstruct. - The default
nameshould be "Unknown". - The default
ageshould be 0. - The
Default::default()method should return aPersoninstance with the default values.
Expected Behavior:
Calling Person::default() should return a Person instance where name is "Unknown" and age is 0.
Edge Cases to Consider:
- Ensure that the
Stringfield is properly initialized with the default value "Unknown". Rust requires this for String fields.
Examples
Example 1:
Input: None (calling Person::default())
Output: Person { name: "Unknown", age: 0 }
Explanation: The `Default::default()` method is called, which should return a Person with the default name and age.
Example 2:
Input: None
Output: let person: Person = Person::default();
Explanation: This demonstrates how to create a Person instance using the default values.
Constraints
- The
namefield must be aString. - The
agefield must be au32. - The default
namemust be the string "Unknown". - The default
agemust be the integer 0. - The solution must compile and run without errors.
Notes
- Remember that the
Defaulttrait requires you to implement thedefault()method. - Consider how to properly initialize the
Stringfield to avoid potential errors. - This exercise reinforces understanding of traits and default values in Rust.