You can experiment with Rust online using the
Rust Playground
without installing anything on your computer. The website at the button
below provides an online compiler to execute programs. It provides options
such as assembly flavor, different versions and releases of Rust, and
executes code in the Miri
interpreter.
The Rust Playground is an open source project which provides features such
as crates (they are a compilation unit, similar to modules in Typescript and
Javascript), code formatting (provided by
rustfmt), code linting
(provided by Clippy),
code sharing,
test execution
with cargo run,
library compilation
with cargo build, and seeing the
assembly output
of your program.
Install Rust
To install Rust locally on your computer, you can use rustup.
If you are running a Linux machine you can also easily run rustup with the
following command:
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
The rustup installer will install rustc, cargo, rustup and other standard
tools to Cargo's bin directory. For more information such as choosing the
install location, installing nightly builds of Rust, or enabling tab
completion is provided in the rustup manual.
rustc is the compiler for the Rust language. Most developers do not use rustc
directly but through cargo (similarly to how make is used). The following
command allows you to see how cargo invokes rustc by printing out each rustc
invokation.
$ cargo build --verbose
Cargo is the Rust package manager.
Similar to how NPM is the Node package manager. Cargo can help download your
dependencies, compile your package, and distribute them to crates.io.
Using Cargo
Starting a project with Cargo is as simple as running cargo new.
$ cargo new hello_world
This will create the Cargo.toml (.toml stands for Tom's Obvious
Minimal Language) file and a src/main.rs file within the the
directory of your package name. The Cargo.toml file is similar
to package.json in NPM or the pom.xml file for Maven.
Inside the Cargo.toml file:
[package]
name = "hello_world"
version = "0.1.0"
edition = "2021"
[dependencies]
Inside the src/main.rs file:
fn main() {
println!("Hello, world!");
}
To compile the crate:
$ cargo build
Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)
This will generate an executable binary with the name of your package.
We can also compile and run the executable all in one step:
$ cargo run
Fresh hello_world v0.1.0 (file:///path/to/package/hello_world)
Running `target/hello_world`
Hello, world!