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.

The Rust compiler is used to compile and link Rust code files. Though we may use it directly (and it is used this way in this book to run the various examples), we mainly use it in practice through cargo.

3.3.1Compiling with rustc

To compile the following rust file:

fn main() {
  println!("Hello world!");
}

We have to run the following command:

This command produces the binary hello that we can run:

Hello world!

3.3.2Handling error messages

In the following code, we have introduced an error. The i variable is defined twice in the same scope. Plus another error a bit below.

struct A {
  i: i8,
  i: i8,
}

fn main() {
  let a = A {i: 1, j: 2};
}

If we try to compile this code:

error[E0124]: field `i` is already declared
 --> hello.rs:3:3
  |
2 |   i: i8,
  |   ----- `i` first declared here
3 |   i: i8,
  |   ^^^^^ field already declared

error[E0560]: struct `A` has no field named `j`
 --> hello.rs:7:20
  |
7 |   let a = A {i: 1, j: 2};
  |                    ^ `A` does not have this field
  |
  = note: all struct fields are already assigned

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0124, E0560.
For more information about an error, try `rustc --explain E0124`.
Fetching long content....

The compiler rustc fails and gives us multiple informations for each error:

  1. The error number: E0124 or E0560.

  2. A short description of the error.

  3. The exact place of the error.

  4. Eventually some hints about the cause or the context of the error.

Finally rustc gives an error count (error: aborting due to 2 previous errors) and explains us how to get more information about these errors.

Here is the output given by rustc when asking for informations about the first error:

A struct was declared with two fields having the same name.

Erroneous code example:

struct Foo {
    field1: i32,
    field1: i32, // error: field is already declared
}

Please verify that the field names have been correctly spelled. Example:

struct Foo {
    field1: i32,
    field2: i32, // ok!
}