4.1 KiB
RustBook
Getting Started
Chapter 01: Installation
Recommendation is to use rustup using the command:
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
To confirm it's installed:
rustup --version
rustup 1.26.0 (5af9b9484 2023-04-05)
Update
To update rustup and please do regularly
rustup update
(
stable-x86_64-unknown-linux-gnu unchanged - rustc 1.76.0 (07dca489a 2024-02-04)
Documentation
rustup comes with documentation, just type
rustup doc
and the browser will open a page with links toward lots of docs.
Chapter 02: Hello, World!
Basically done in 3 steps:
- Edit the rs file
- Compile using
rustc
- Call the executable
Work folder is Projects/01_HelloWorld
, where we create the file main.rs
fn main() {
println!("Hello, World!");
}
To execute this program:
cd Projects/01_HelloWorld/
rustc main.rs
./main
Hello, World!
The program works, I'm now done.
Note
All rust program starts by calling the function main
.
Functions with !
appended to their name, like println!
, are macros.
Chapter 03: Hello, Cargo!
Make sure Cargo is installed
cargo --version
cargo 1.76.0 (c84b36747 2024-01-18)
New project with Cargo
cargo new Projects/hello_cargo
tree Projects/hello_cargo
Projects/hello_cargo ├── Cargo.toml └── src └── main.rs 2 directories, 2 files
Cargo creates:
- a directory with the project name given,
- and a project with the same name
The Cargo configuration file Cargo.toml
in the root folder and
the projcet code in the src/
directiory is what makes it a Rust project.
Building with Cargo
From the root folder, run
cargo build
This will create a Cargo.lock
file in the root directory, and
an executable in src/target/debug/hello_cargo
.
Which means you can display the text "hello, World!" by calling directly the file
./target/debug/hello_cargo
Hello, world!
Running a cargo
You can both build and run the program with
cargo run
Hello, world!
Checking a cargo
Cargo can check if the program can compile. It doesn't execute it.
cargo check
Finished dev [unoptimized + debuginfo] target(s) in 0.01s [ Babel evaluation exited with code 0 ]
Releasing a cargo
To build a cargo with an optimised build, run
cargo build --release
tree
. ├── Cargo.lock ├── Cargo.toml ├── src │ └── main.rs └── target ├── CACHEDIR.TAG └── release ├── build ├── deps │ ├── hello_cargo-ac6d8d77e18d4d6b │ └── hello_cargo-ac6d8d77e18d4d6b.d ├── examples ├── hello_cargo ├── hello_cargo.d └── incremental 8 directories, 8 files
The build results are in the folder target/release/
now.