Create a new folder, and in the terminal type:
cargo init
This makes Cargo initialise a new Rust repository. Cargo will take care of most of the work for you.
The file structure is as follows:
- Cargo.toml
- src/
- main.rs
cargo.toml is the configuration file for our Rust project. It includes our dependencies, project name, authors, the version of Rust we are using and more.
When we have just ran cargo init, our file will look like this:
[package]
name = "Hello_world"
version = "0.1.0"
authors = ["bee <bee@fake.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Our main.rsfile in the folder src is the main file where we write our code. Every single Rust project must have a main file, and every main file must have a main function.
fn main() {
println!("Hello, world!");
}
In Rust, we use curly braces to denote blocks of code. And a semi-colon to express the end of an expression.
To print in Rust, we use the macro println!.
We know println is a macro, as it is called with an exclamation mark. Macros, in a nutshell, allow us to write code that writes more code. To put it even simpler, we can create our own syntax that translate to different code.
To directly run this program, we execute:
cargo run
This should result in:
➜ cargo run
Compiling hello_world v0.1.0 (/tmp/hello_world)
Finished dev [unoptimized + debuginfo] target(s) in 0.21s
Running `target/debug/hello_world`
Hello, world!
This command:
- Compiles the code with the unoptimised build (to increase the speed of compilation)
- Runs the code
You’ll also notice a new folder has been created, target.
target contains the binaries for our project.
- Cargo.toml
- src/
- main.rs
- target/
- debug/
= build/
- deps/
- examples/
- hello_world
- hello_world.d
- incremental/
Right now, the only important file is hello_world
This file is actually the binary for our program.
We can tell its a binary by running file on the target file or by running ls -l in the directory
drwxr-xr-x - bee 31 Jul 23:35 build
drwxr-xr-x - bee 31 Jul 23:35 deps
drwxr-xr-x - bee 31 Jul 23:35 examples
.rwxr-xr-x 2.9M bee 31 Jul 23:35 hello_world
.rw-r--r-- 72 bee 31 Jul 23:35 hello_world.d
drwxr-xr-x - bee 31 Jul 23:35 incremental
To build our project without running it, run:
cargo build
And now we can run the binary directly.
./target/debug/hello_world
This is exactly the same as cargo run, but 2 commands.
When we want to build our project and optimise it, run it with the release profile:
cargo build --release
Use the normal cargo build for quick checking of the code. Use the release argument to optimise the code to the maximum possible that the Rust compiler will allow.
We call --release a profile, specifically the release profile. The Rust compiler has different levels of optimisation depending on what you want.