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.

Most of the Rust examples of the book are written in a simplified way in order to be more readable and help to concentrate on the main topic. However this makes these examples not compilable with just a copy & paste. We are going to see how to recognize what is missing, and how to complete these examples.

2.5.1Missing main function

The first important thing is that they do no contain the main() function that is compulsory for compiling and running. Example:

Hello!

Such an example cannot be compiled as-is. It needs to be wrapped inside a main() function, as following:

2.5.2Printed expression on last line

The second particularity is that many examples print one or more values at the end of the code snippet, with an expression that does not end with a semicolon:

18

In the last line is a perfect Rust expression that we could use for instance as a value to return from a function. However in this context, if we wrap it inside a main() function this will lead to an error, as the main() must return nothing, except an integer or an error. To run such an example we must wrap the last line’s expression into a println!() macro as following:

2.5.3Multiple code snippets

Some Rust examples are split into several code snippets. As with the bash examples, the first cell is tagged on its right with start and the last cell with stop. To run them, just paste them together, but pay attention to the last line of each snippet as it could be an expression without a semicolon.

Here is the first part of an example:

10

The second part:

8

And the last part:

18

To run it, just paste all lines together, wrapping last lines containing an expression into a println!() macro, and putting all this code into a main() function, as following:

fn main() {
  let a = 10;
  println!("{:?}", a);
  let b = 8;
  println!("{:?}", b);
  println!("{:?}", a + b);
}