A struct is a compound data type, which means that within the struct there can be a variety of data types. Structs give each element contained within it a name, which is often referred to as a field or member. Below is a very basic implementation of a struct,

struct Stuff {  
    value: i32,
    value2: f64,
    value3: char,

If you're coming from JavaScript you'll notice a few things about this code snippet: the type must be declared, the format of a struct looks a lot like an object, and there is a trailing comma. We don't have to delve deep into these differences right now, but we can keep them in mind for future posts.

To create an instance of our Stuff struct we need to use the let keyword, we can assign values using an object literal notation and once the struct is instantiated we can also modify values using dot notation (requires the mut keyword).

Tuple structs

Tuple structs are not as commonly used as the regular C style structs, but they do have their uses. The difference between a normal struct and a tuple struct is that the latter does not have named fields.

struct Rectangle(i32, i32, i32);

The above code creates a Rectangle struct that takes three integer values. This is also easily accomplished, and easier to read, with a normal struct. One use that tuple structs have is with regards to the newtype pattern which allows the creation of a new type. This benefit is easier to show in code

struct Meters(i32);

let length = Feet(3);

let Meters(integer_length) = length;  
println!("length is {} inches", integer_length);  

This code will assign 3 to integer_length and allow extraction of the inner integer with let (a broader pattern).

Unit structs

Unit structs are a special type of struct that do not have fields and are primarily used with generics (which is out of the scope of this article). A unit struct is declared and instantiated below,

struct Nil;

let unit_struct = Nil;  

There's not much else to unit structs, but expect more when we go into generics.


Of course, Rust structs can use methods and the syntax for writing one looks like this,

impl Monster { //Monster is the name of the struct  
    fn attack(&self) { //refers to a borrowed pointer
        println!("The monster attacks for {:d} damage.", self.attack);

That excellent example was brought to you by Rust for Rubyists which is an excellent resource for those of you who are learning Rust after a scripting language like Ruby or JavaScript.


That brings us to the end of a very, very quick glimpse into Rust structures. We'll be diving more in depth into a variety of Rust's data structures in the coming weeks so stay tuned!


Rust , Structs , Structures

About the author
comments powered by Disqus