Composite data types
You won't get too far without defining composite types to strap data together (unless you like pain). I suppose most programmers are used to classes, most of them may also know enums. Rust also has those, but with some twists.
Tuples
Tuples are the most basic composite data type. They don't have names and consist of fields of independent types, only discerned by their position. They are useful if you want to bundle data in a single context, since tuples are defined in-place. Most notable, they allow you to return multiple values from functions.
let tuple: (usize, &str, usize, &str) = (42, "answer", 69, "fun");
Structs
Structs in Rust refer to all named composite types with a single variant. They come in three forms:
- No fields at all, so they can't carry data. They can be used for polymorphism or as parameters for generics, but more on that in their respective chapters. They are zero-sized, so they don't occupy any memory.
- Unnamed fields, only identifiable by their position. Field access works exactly like with a tuple, only that structs provide a name for the type. A struct used to wrap another value is typically implemented by using a single unnamed field.
- Named fields. This behaves like structs or classes in the languages you probably already know.
struct NoFields;
struct UnnamedFields(usize, bool);
struct NamedFields {
some_field: usize,
another_field: bool
}
Enums
As it is the case with structs, enums are also much more flexible than their equivalents in many other languages. They essentially behave like structs with multiple variants, but more on that in its own chapter.