dhghomon.github.io/easy_rust/Chapter_24.html
1 Users
0 Comments
18 Highlights
0 Notes
Tags
Top Highlights
The third type is the named struct. This is probably the most common struct.
Structs
With structs, you can create your own type.
You will use structs all the time in Rust because they are so convenient. Structs are created with the keyword struct. The name of a struct should be in UpperCamelCase (capital letter for each word, no spaces). If you write a struct in all lowercase, the compiler will tell you.
There are three types of structs.
One is a "unit struct". Unit means "doesn't have anything". For a unit struct, you just write the name and a semicolon.
struct FileDirectory;
The next is a tuple struct, or an unnamed struct. It is "unnamed" because you only need to write the types, not the field names.
Tuple structs are good when you need a simple struct and don't need to remember names.
struct Colour(u8, u8, u8);
let my_colour = Colour(50, 0, 50); // Make a colour out of RGB (red, green, blue)
Note that you don't write a semicolon after a named struct, because there is a whole code block after it.
In this struct you declare field names and types inside a {} code block.
struct SizeAndColour { size: u32, colour: Colour, // And we put it in our new named struct }
If the field name and variable name are the same, you don't have to write it twice.
struct Country { population: u32, capital: String, leader_name: String }
Did you notice that we wrote the same thing twice? We wrote population: population, capital: capital, and leader_name: leader_name. Actually, you don't need to do that
let population = 500_000; let capital = String::from("Elista"); let leader_name = String::from("Batu Khasikov"); let kalmykia = Country { population, capital, leader_name, };
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.