Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

In Rust, a structure is defined using the struct keyword, as in the following example that defines a Book data type:

We initialize an instance of a struct by setting a value for each field:

To retrieve a field’s value, we simply name the field we want to access on the instance:

("La Nuit du carrefour", "Georges Simenon", 1931)

If we define the three following variables:

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:

Here is the instance’s content:

("Mon ami Maigret", "Georges Simenon", 1949)

Here is the result:

("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.