Structs
Often you need to keep several values of possibly different types together in your program, for example, the scores of the players. Let us say that the score
contains numbers indicating the health
of the players and the level at which they are playing. The first thing you can do to clarify your code is to give these tuples a common name, like:
struct Score;
Or better still, indicate the types of the values:
struct Score(i32, u8);
And we can make a score like this:
// from Chapter 4/code/structs.rs let score1 = Score(73, 2);
These are called tuple structs because they resemble tuples very much.The values contained in them can be extracted like this:
let Score(h, l) = score1; // destructure the tuple println!("Health {} - Level {}", h, l);
This prints the following output:
Health 73 - Level 2
A tuple struct with only one field (called a newtype) gives us the possibility to create a new type based on an old one, so that both have the same memory representation. Here is an example:
struct...