In Rust, a structure is defined using the struct keyword, as in the
following example that defines a Book data type:
struct Book {
title: &'static str,
author: &'static str,
year: i16,
}We initialize an instance of a struct by setting a value for each
field:
let book1 = Book {
title: "La Nuit du carrefour",
author: "Georges Simenon",
year: 1931,
};To retrieve a field’s value, we simply name the field we want to access on the instance:
(book1.title, book1.author, book1.year)("La Nuit du carrefour", "Georges Simenon", 1931)If we define the three following variables:
let title = "Mon ami Maigret";
let author = "Georges Simenon";
let year: i16 = 1949;We can use them to create a Book instance. The names of the variables,
because they match the names of the fields, will be used by the compiler
to know how to initialize the Book instance:
let book3 = Book {
title,
author,
year,
};Here is the instance’s content:
(book3.title, book3.author, book3.year)("Mon ami Maigret", "Georges Simenon", 1949)let book2 = Book {
title: "Le Chien jaune",
..book1
};Here is the result:
(book2.title, book2.author, book2.year)("Le Chien jaune", "Georges Simenon", 1931)For constructing an object, we do not usually use directly the curly
braces syntax, but define a constructor method, named new() by
convention. We will see the new() method in the next chapter.