Rust By Example: Structs

Опубликовано: 13 Апрель 2026
на канале: Stephen Blum
256
3

So, we're starting to learn Rust, a language that allows us to build more complex applications using more advanced structures and enumerations. Let's kick things off with structures. Basically, structures allow us to group together variables.

Instead of assigning a single value to a variable, like a number or a string, we can use a structure to store several related variables. This is handy when we need an organized way to track multiple variables together. Think of it as creating a simple profile for an object, with each variable representing different attributes.

Consider a person, a person has a name and an age. Those two properties can be defined in a structure as a string and an unsigned 8-bit integer, respectively. The 8-bit integer, a number limited to the range of 0 to 255, fits well for this as we don't encounter a lot of people older than 255 years! Another kind of structure is a fieldless struct or unit struct, this doesn't have any specified format and provides a placeholder that you can extend according to your needs.

This is an advanced feature and we won't focus much on this for now. Most times, you'll want to use the simple structure that allows you to define attributes of an object. And you can even bundle structures together! For example, a rectangle can be defined as two points, top left and bottom right, each of which is a structure onto itself with x and y coordinates.

Structures allow us to give an organized, structured shape to our data and enable us to reuse them as required. You can create a person or a point, or any other structure, and access their properties using the dot notation, like point.x or point.y. Another interesting feature is what I call 'copying structures', you can reuse a defined structure and copy over its values to a new one.

This coupled with the ability to pull out values from structures into individual variables gives us a lot of flexibility in manipulating data. Lastly, we also can use tuple style initialization for structures where the order of values is important, like coordinates, latitude and longitude, or IP addresses. These structures don't have named variables; instead, it follows an arranged order.

Wow, Rust seems pretty engaging! With these introductory features, you should be well on your way to becoming a Rust programmer. And remember, this is just the start, there are lots of other features in Rust waiting for you to discover!