Rust for starters (Part- 2 Structs)

Doga Budak
3 min readDec 30, 2023

--

Studying rust always gives me joy. And while I was writing my new library, I thought why am I not writing a second chapter for me beloved story.

Since I am writing these blogs for fun, I will also go in a mixed order most probably and cover the most important aspects of this programming language. So what I think about importance could be different then yours, but hey! I learned it from hard way.

Structs

In Rust, a struct is a compound data type that allows you to group together variables of different types under a single name. It's a fundamental building block for organizing and encapsulating related data.

pub struct ApiKeys {
public_key: String,
private_key: String,
}

As you can see here I created a public struct called ApiKeys, has 2 elements inside. public_key and private_key. These 2 keys have the primitive type of String. Easy right ?

After a struct has been defined, we create an instance of it and give each field a concrete value in order to use it. The struct name is used to create an instance, and curly brackets containing key:value pairs — the fields’ names as keys and the data we wish to store in them as values — are then added. The fields don’t need to be specified in the same order that they were declared in the struct. Stated differently, the struct definition functions as a kind of general template for the type, which instances then fill in with specific data to produce values of the type.

let keys1 = ApiKeys {
public_key:"public_key",
private_key: "private_key"
}

I think you can relate to this. Whenever we define an object (like JSON, for people who are familiar with javascript world.) we must specify the type for it. Just like typescript's no-any rule right ? So in this case we can find the equivalent of structs in typescripts. It is interface !

To get a specific value from a struct, we use dot notation. So from this example keys.private_key would give us "private_key". You can also use the same notation to change a value in struct.

keys1.public_key = String::from("new public key")

Create instances from other instances

Yeah this is something I also learned recently, kinda resembles javascript's `…` notation.

Lets imagine we the same struct but a bit more extended.

pub struct ApiKeys {
public_key: String,
private_key: String,
ttl : u64,
active: bool
}

I want to define a key2 which shares a lot of aspect from key 1. As simple as typescript I can create it like this;

let key2 = ApiKeys {
public_key: String::from("another_public_key"),
private_key: String::from("another_private_key"),
..key1
};

You can see here that key2 has same ttl and same active flag as key1, but has different public and private keys. This would allow you to create objects in a cleaner way and keeps away potential bugs.

Thanks for reading, Part 3 will follow

--

--