WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 12 of 100

How do you create a struct in Rust? Provide a simple example.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, a struct is a way to group related data together into a single, custom data type. You can create a struct using the ‘struct‘ keyword followed by the name of the struct and the fields the struct contains.

Here’s a simple example:

    struct Person {
        name: String,
        age: u32,
        is_student: bool,
    }

In this example, we’re defining a ‘Person‘ struct with three fields: ‘name‘ of type ‘String‘, ‘age‘ of type ‘u32‘, and ‘is_student‘ of type ‘bool‘.

To create an instance of this struct, we can use the following syntax:

    let person = Person {
        name: String::from("Alice"),
        age: 25,
        is_student: true,
    };

In this example, we’re creating a new ‘Person‘ instance and assigning it to the ‘person‘ variable. We’re using the curly brace syntax to specify the values for each field. Note that we’re using ‘String::from()‘ to create a new ‘String‘ object for the ‘name‘ field.

We can access fields of the struct using dot notation, like so:

    println!("Name: {}", person.name);
    println!("Age: {}", person.age);
    println!("Is student: {}", person.is_student);

This will output:

    Name: Alice
    Age: 25
    Is student: true

Overall, using structs is a powerful way to organize data and make your code more expressive in Rust.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics