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:
bat hello.rsfn main() {
println!("Hello world!");
}
We have to run the following command:
rustc hello.rsThis command produces the binary hello that we can run:
./helloHello 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.
bat hello.rsstruct A {
i: i8,
i: i8,
}
fn main() {
let a = A {i: 1, j: 2};
}
If we try to compile this code:
rustc hello.rserror[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`.
The compiler rustc fails and gives us multiple informations for each error:
The error number:
E0124orE0560.A short description of the error.
The exact place of the error.
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:
rustc --explain E0124A 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!
}