Defining Methods on Structs with `impl`
We've learned how to define structs to store data. Now, let's learn how to add behavior to our structs by defining methods. Methods are functions that are associated with a specific struct and can operate on its data.
Generics in Structs and Enums
In our previous exploration of Generic Data Types, we saw how to reduce code duplication by creating generic functions. Now, we'll extend this powerful concept to our custom data types. This article dives into how to define and use generics in structs and enums, allowing us to build flexible, reusable data structures that are central to idiomatic Rust.
Introduction to Structs: Creating Custom Data Types
Welcome to Chapter 2! We've built a solid foundation with Rust's basic data types, collections, and control flow. Now, we're going to start exploring some of Rust's more powerful features that allow you to create complex and expressive programs.
Ownership in Action: A Practical Example
Throughout this series, we have explored the intricate rules of Rust's ownership system, from moves and copies to immutable and mutable borrows. Now it's time to consolidate that knowledge. This article brings everything together in a single, practical example, demonstrating how these concepts work in harmony to create a safe and efficient program.
Project: Modeling a User Account
It's time to put everything we've learned about structs into practice. In this project, we will model a user account for a web application. This will involve defining a User struct, creating instances of it, and defining methods to interact with the user data.
Project: Rectangle Area Calculator (Part 1)
To solidify our understanding of structs, let's build a simple program that calculates the area of a rectangle. This project will be broken into two parts. In this first part, we will focus on defining the Rectangle struct and creating a simple main function to work with it.
Project: Rectangle Area Calculator (Part 2)
In Part 1 of this project, we wrote a program that calculates the area of a rectangle using a standalone function. This works, but we can make the code clearer and more organized. The area function is directly related to the Rectangle struct, so it should be a method of the struct.
Structs and Ownership
We've learned about structs and we've learned about ownership. Now, it's time to see how these two concepts interact. Understanding how ownership works with structs is crucial for writing correct and efficient Rust code.
The `Debug` Trait and Printing Structs
So far, when we've wanted to inspect a value, we've used the println! macro with the {} format specifier. However, if you try to do this with a struct you've defined, you'll run into an error.
Tuple Structs and Unit-Like Structs
In the previous article, we learned how to define structs with named fields. Rust also provides two other variations of structs that are useful in different scenarios: tuple structs and unit-like structs.