Code Logo

Access Struct Fields with .

Published at25 Jul 2026
Rust Data Structures Easy 0 views
Like0

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

Example 1
Input
("Charlie",40)
Output
Charlie
Explanation

Another name

Example 2
Input
("Eve",35)
Output
Eve
Explanation

Final name

Example 3
Input
("Alice",30)
Output
Alice
Explanation

Access name field of Person

Example 4
Input
("Diana",22)
Output
Diana
Explanation

Yet another

Example 5
Input
("Bob",25)
Output
Bob
Explanation

Different name

Algorithm Flow

Recommendation Algorithm Flow for Access Struct Fields with .
Recommendation Algorithm Flow for Access Struct Fields with .

Solution Approach

struct Person {
    name: String,
    age: i32,
}

fn solution(name: String, age: i32) -> String {
    let p = Person { name, age };
    p.name
}

Best Answers

rust - Approach 1
struct Person {
    name: String,
    age: i32,
}

fn solution(name: String, age: i32) -> String {
    let p = Person { name, age };
    p.name
}