Chapter1 Getting started
In this chapter, we'll discuss:
- Installing Rust on Linux, macOS and Windows
- Writing a program that prints
Hello, World!- Using cargo, Rust's package manager and build system
Create a HelloWorld Project
Firstly, install Rust by using the command line tool: rustup.
Now we can create a "Hello world" app:
-
Creating a project directory
-
writing and running a Rust program
fn main() {
println!("Hello world");
} -
Compiling and running are separated steps.
Before running a Rust program, you must compile it using the Rust compiler by entering the
rustccommand and passing it the name of your source file:rustc main.rs.Rust is an ahead-of-time compiled language.
Next, we'll introduce the Cargo tool, which will help you write real-world Rust porgrams.
-
Cargo is Rust's build system and package manager. You can use it to:
- Building your code
- Downloading the libraries your code depends on
- Building those dependencies
-
Create a project with Cargo:
cargo new hello_cargo
cd hello_cargoIt creates the following files/folders for us:
-
main.rsfile -
Cargo.tomlfile -
.gitfolder -
srcfolder -
.gitignorefile
You may use different VCS other than GIT by specifying the
--vcsflag. -
-
Inside the
Cargo.tomlfile is the configuration for our project:[pakcage]: is a section heading that indicates that the following statements are configuring a pacakge.[dependencies]: is a the start of a section for you to list any of the project's dependencies.(In Rust, packages of code are referred to as crates)
-
Rust expects all the source files to live inside the
srcfolder. Using Cargo helps you to organize your projects.
Building and Running a Cargo Project
-
Build your project with:
cargo build -
Run the executable with:
./<executable-name> -
But we can compile the code and then run the resulting executable all in one command:
cargo runThe resulting executable can be found inside the
target/debugdirectory. -
If you are continually checking your work while writing the code, using
cargo checkwill speed up the process. -
When ready for release, you can use
cargo build --releaseto compile your proejct with optimizations. This will create an executable intarget/releasedirectory.