learn-rust

Free Rust ๐Ÿฆ€ course in English ๐Ÿ‡ฌ๐Ÿ‡ง

View on GitHub

Table of Contents๐Ÿ“š

Hello world with cargo๐Ÿšข

What is cargoโ“

Cargo is a Rust package manager. It is used to manage dependencies and build Rust projects.

Creating a new project๐Ÿ†•

We will create a new project called hello-world-cargo, to do this, we will use the following command.

โ„น๏ธ the --bin parameter flags the project as an application, not a library.

$ cargo new hello-world-cargo --bin

> Created binary (application) `hello-world-cargo` package.

This command created a new folder ๐Ÿ“‚ hello-world-cargo in the current directory.

This folder contains a ๐Ÿ“„ Cargo.toml file, a ๐Ÿ“‚ src folder and a ๐Ÿ“„ main.rs file.

hello-world-cargo
โ”œโ”€โ”€ Cargo.toml
โ”œโ”€โ”€ .git
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ .gitignore
โ””โ”€โ”€ src
    โ””โ”€โ”€ main.rs

It also initialized a git repository for the project.

The ๐Ÿ“‚ src folder contains the source code of the application, in it there already is a ๐Ÿ“„ main.rs file containing an hello world program.

// ๐Ÿ“„ main.rs
fn main() {
    println!("Hello, world ๐Ÿ‘‹");
}
File Description
๐Ÿ“„ Cargo.toml The Cargo manifest file, this file contains all the dependencies and the application name.
๐Ÿ“‚ src The source folder, this folder contains the source code of the application.
๐Ÿ“„ main.rs The main file, this file contains the source code of the application.
๐Ÿ“‚ .git The git folder, this folder contains all the git files, you can ignore this folder if you donโ€™t use git.
๐Ÿ“„ .gitignore The git ignore file, this file contains all the files that should be ignored when committing.

Compiling and running a program with cargo๐Ÿƒ

Just compiling

To compile the program, we will use the cargo build command.

# hello-world-cargo ๐Ÿ“‚
$ cargo build

This command will compile the program and create an executable file called ๐Ÿ“„ hello-world-cargo in the new ๐Ÿ“‚ target/debug folder.

# hello-world-cargo/target/debug ๐Ÿ“‚
$ ./hello-world-cargo
> Hello, world ๐Ÿ‘‹

Compiling and running๐Ÿƒ

To compile and run the program, we will use the cargo run command.

# hello-world-cargo ๐Ÿ“‚
$ cargo run
...
> Hello, world ๐Ÿ‘‹


Home ๐Ÿ  - Next Section โญ๏ธ


Course created by SkwalExe and inspired by Dcode