Structs
⭐️ Structs are used to encapsulate related properties into one unified datatype.
💡 By convention, the name of the struct starts with a capital letter and follows CamelCase.
There are 3 variants of structs, 1. C-like structs
one or more comma separated name:value pairs
brace-enclosed list
similar to classes (without it’s methods) in OOP languages
because fields have names, we can access them through dot notation
Tuple structs
one or more comma separated values
parenthesized list like tuples
looks like a named tuples
Unit structs
a struct with no members at all
it defines a new type but it resembles an empty tuple, ()
rarely in use, useful with generics
⭐️ When regarding OOP in Rust, attributes and methods are placed separately on structs and traits. Structs contain only attributes, traits contain only methods. They are getting connected via impls.
C-like structs
Tuple structs
⭐️ When a tuple struct has only one element, we call it new type pattern. Because it helps to create a new type.
Unit structs
This is rarely useful on its own, but in combination with other features, it can become useful.
📖 ex: A library may ask you to create a structure that implements a certain trait to handle events. If you don’t have any data you need to store in the structure, you can create a unit-like struct.
Last updated