DEV Community

Cover image for Day 11: Structs in Rust - Laying the Foundation πŸ—οΈ
Aniket Botre
Aniket Botre

Posted on

Day 11: Structs in Rust - Laying the Foundation πŸ—οΈ

Hello fellow code adventurers! On Day 11 of my #100DaysOfCode Rust expedition, let's unravel the world of Structs - the architects of custom data types.


The Concept: A Quick Blueprint πŸ“‹

Structs in Rust serve as a way to bundle different data types together under a single umbrella. They act as blueprints for constructing personalized data entities.

It overcomes the limitation of a traditional array that can only contain elements of the same data type. A structure can also contain a structure in itself. In Rust, structures are similar to tuples, but structure elements are easily accessible since they are named instead of indexed in the case of tuples.

To define a struct in Rust, you use the struct keyword followed by the name of the struct and a block of curly braces. Inside the curly braces, you define the fields of the struct along with their types.

Once you have defined a struct, you can create instances of it by using the struct's name followed by curly braces containing the values for each field.

For example:

// Defining a struct named `Person`
struct Person {
    name: String,
    age: u32,
    is_programmer: bool,
}

// Creating an instance of the `Person` struct
let john = Person {
    name: String::from("John Doe"),
    age: 30,
    is_programmer: true,
};
Enter fullscreen mode Exit fullscreen mode

In this example, the Person struct encapsulates three fields: name, age, and is_programmer. Creating an instance allows us to provide specific details for each field.


Accessing Struct Fields

You can access the fields of a struct using dot notation (.) followed by the field name.
For example:

println!("Name: {}", person.name); // John Doe
println!("Age: {}", person.age); // 30
Enter fullscreen mode Exit fullscreen mode

In the above example, we access the name and age fields of the person struct and print their values.


Mutating Struct Fields🎚️

By default, struct fields are immutable. However, you can make them mutable by using the mut keyword.

For example:

let mut person = Person {
    name: String::from("John"),
    age: 25,
};

person.age = 26;
Enter fullscreen mode Exit fullscreen mode

In the above example, we make the person struct mutable and then update the value of the age field.


Ownership Rules: Navigating Memory Waters 🧭

When it comes to ownership and borrowing with structs, Rust adheres to its trusted principles. Structs can either own their data or borrow references to data. This ownership system ensures memory safety without compromising performance.

struct Book {
    title: String,
    author: String,
}

fn main() {
    let book1 = Book {
        title: String::from("The Rust Programming Language"),
        author: String::from("Steve Klabnik and Carol Nichols"),
    };

    let book2 = Book {
        title: String::from("Programming Rust"),
        author: String::from("Jim Blandy and Jason Orendorff"),
    };

    let borrowed_book = get_book_title(&book1);

    println!("Book 1 title: {}", book1.title); 
    // Book 1 title: The Rust Programming Language

    println!("Borrowed Book title: {}", borrowed_book);
    // Borrowed Book title: The Rust Programming Language
}

fn get_book_title(book: &Book) -> &String {
    &book.title
}
Enter fullscreen mode Exit fullscreen mode

Here, book1 and book2 own their respective data, while get_book_title borrows a reference to a book's title. Understanding these ownership patterns is pivotal for writing robust Rust code.


Conclusion

Structs in Rust harmonize seamlessly with other language features like enums, paving the way for the creation of intricate data structures. As we progress on our Rustic journey, we'll soon delve into implementing methods on structs.

Stay tuned for more Rust adventures on Day 11! Happy coding! πŸ’»πŸš€βœ¨

RustLang #Programming #LearningToCode #CodeNewbie #TechJourney #Day11

Top comments (0)