Skip to content

Learning Rust - Structs & Collections

Posted on:March 18, 2023 at 03:22 PM

Compile checker

Rust compile checker is kind of hard to work with if you don’t fully grasp the way it implements its ownership system. I’ve been struggling more with the compiler trying to run my code than thinking about the way of doing it.

That, of course, doesn’t mean that I’m right, quite the opposite actually. It means that I’m still thinking in how to write code in a language that does not care at all how memory efficient it can be. I’m loving the exercise of having to think about how the computer is actually going to treat the changes in data and references I’m doing.

Structs

Structs work just like classes do, they are ways of organizing fields and methods for a type of data. We still need to handle ownership for the values that use the Heap and also the privacy of the fields. Fields and functions can be declared public (because they are normally not), by using pub before their definitions.

Methods are done by implementing the functionalities of them, just like when using the derive with a trait.

Enum

Enums here have capabilities to hold or use data but it’s the same concept, if they don’t have any type they recieve numbers intenally in the order declared. It’s also posible to declare an enum with its types:

enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);

I also go introduced to the Option<T> enum, which makes it so a value can have either a value or note, for that an Option enum can either be a Some or a None, representing a non-value. To catch every case from an Option, we can use the match expression. It has several arms that express what to do in every case of an Option. It can also be used with any enum, the only condition is that every enum case should be handled.

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

Collections

Vectors

Vectors are like arrays but have some functionalities that other collections have to like getting an iterator from it. Vectors hold data of the same type.

String

Even though the concept in high level languages of a string is normally a single value, in Rust strings are a collection of characters saved in the heap that store their data enconded in UTF-8, that makes them not working necessarilly how one will expect because of characters that take multiple bytes for a single “graphameme”.

Hash map

Hash maps are objects or dictionarys that store keys with their respective values. They can be iterated like if it’s an enumeration with the a tuple of key and value.