Hone logo
Hone
Problems

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 Person with name: String and age: u32 fields.
  • Implement the Default trait for the Person struct.
  • The default name should be "Unknown".
  • The default age should be 0.
  • The Default::default() method should return a Person instance 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 String field 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 name field must be a String.
  • The age field must be a u32.
  • The default name must be the string "Unknown".
  • The default age must be the integer 0.
  • The solution must compile and run without errors.

Notes

  • Remember that the Default trait requires you to implement the default() method.
  • Consider how to properly initialize the String field to avoid potential errors.
  • This exercise reinforces understanding of traits and default values in Rust.
Loading editor...
rust