Access Struct Fields with .
Write a Rust function that defines a Person struct with name: String and age: i32 fields, then returns the name of a given Person instance using dot notation. The dot operator (.) in Rust is used to access fields and methods of structs and other types.
Structs in Rust are custom data types that bundle related values together. Named field structs are the most common form, where each field has a name and a type. You access fields with the dot syntax: person.name or person.age. This syntax is consistent across all struct instances and works with both owned values and references.
Rust's struct field access is resolved at compile time. The dot operator has the highest precedence of any operator and automatically dereferences as needed. When accessing a field through a reference (&person), Rust implicitly follows the reference to access the underlying struct's field.
Time complexity is O(1) as struct field access is a fixed offset from the struct's base address. Space complexity is O(1) as the fields are stored inline within the struct's memory layout.
Edge cases include empty name strings, negative age values, and ensuring the struct definition is visible to the function. The struct can be defined locally within the function or globally depending on the compiler's reachability rules.
Example Input & Output
Another name
Final name
Access name field of Person
Yet another
Different name
Algorithm Flow

Solution Approach
Best Answers
struct Person {
name: String,
age: i32,
}
fn solution(name: String, age: i32) -> String {
let p = Person { name, age };
p.name
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
