Introduction to Structs in Rust
Introduction to Structs
Hello! In this lesson, we will dive into one of Rust's fundamental features — structs. Structs are a powerful way to package related data together, making your code more organized and easier to manage.
In this lesson, we will cover how to define structs, create instances, access and modify their fields. By the end of this lesson, you will have a solid understanding of Rust structs and will be ready to use them in your own projects.
Let's get started!
Aside: Is Rust an Object Oriented Language?
Rust supports many features associated with object-oriented programming (OOP), but it doesn't strictly adhere to traditional OOP principles as seen in languages like Java or C++. Let's take a look at some common features of OOP.
Objects and Classes
Rust does not have a concept of classes or objects as seen in other programming languages. However, Rust allows the grouping of data and functionality into a single data structure called a struct, similar to an object.
Encapsulation
Rust also supports another OOP paradigm known as encapsulation. The concept of encapsulation helps in managing complexity by hiding the internal state of the object from the outside world and exposing only what is necessary through a defined interface.
Inheritance
Rust does not support inheritance. Inheritance allows a class to derive properties and behavior (methods) from another class. The class that inherits is called the "subclass," and the class being inherited from is called the "superclass." Rust does not have any features that allow a struct to inherit fields or methods from other structs.
Polymorphism
Rust supports polymorphism using traits and generics which we will cover later in this course. Polymorphism allows objects of different types to be treated as objects of a common supertype.
Defining a Struct
A struct (short for "structure") in Rust is a custom data type that allows you to group together related data. Imagine you are writing a program to manage a library. You will need to keep track of various information about each book, such as its title, author, and the number of pages. Instead of using separate variables for each attribute, Rust allows you to group these related pieces of data into a single, cohesive unit called a struct. Let's explore how to define a struct using the book analogy.
In Rust, a struct is defined using the struct keyword, followed by the struct's name and a block of fields. Each field has a name and a type. Here’s an example to illustrate:
In this code, we defined a struct named Book with three fields: title, author, and pages. Each field has a specific type: String for title and author, and u32 for pages. Note that when defining a struct, the last field can optionally end with a comma, and no semicolon is needed after the definition.
