Skip to main content

Hello World (first programs) · Beginner · 15 min

Hello World in Rust: rustup, Cargo and your first crate

By Padding · Updated 18 Nov 2026
Debian 13 (rust:1.100 image) · Rust 1.100.0 · Cargo 1.100.0

You will install Rust 1.100 with rustup, create and run a Cargo project, compare debug and release builds, and read a number from the keyboard with proper error handling.

On this page

Rust is a compiled systems language that gives you the speed of C and C++ without manual memory bugs. The compiler checks, before your program ever runs, that every piece of memory has exactly one owner and that nothing is used after it is freed. The price is a strict compiler; the reward is that its error messages are some of the most helpful in any language, and they usually tell you how to fix the problem.

Two tools come with Rust and you will use both from the first minute. rustup installs and updates the compiler (rustc) and lets you switch between versions. Cargo is the build tool and the package manager in one: it creates projects, compiles them, runs them, downloads libraries (called crates) and records exactly which versions you used. Most Rust developers rarely call rustc directly.

In this tutorial you install Rust with rustup, write Hello World with Cargo, compare a debug build with a release build, read a number from the keyboard and handle bad input without crashing, and read your first borrow-checker error. Everything was written for Rust 1.100.0; any Rust from 1.85 onwards runs the code here.

Step 1 · Install Rust with rustup

Rust needs a C linker to produce the final program, so install the C build tools first, along with curl to fetch the installer:

Bash
sudo apt update
sudo apt install -y curl build-essential

On macOS, run xcode-select --install instead, which installs Apple's linker.

Now run the official rustup installer. It downloads a small script from rustup.rs and runs it as your user, not as root:

Bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

--proto '=https' --tlsv1.2 makes curl refuse anything but a secure HTTPS connection, and -sSf keeps it quiet unless something fails. When the installer asks, press Enter for option 1, the standard installation. It puts everything in your home directory: the tools in ~/.cargo/bin and the toolchains in ~/.rustup. Nothing goes into system folders, so you never need sudo for Rust itself.

Load the new path into the shell you are using; new terminals pick it up on their own:

Bash
. "$HOME/.cargo/env"

If you pay for data by the megabyte, note that most of the download is the compiler and the standard library, which every install needs. The default profile also installs the offline documentation, Clippy and rustfmt. Running the installer with sh -s -- --profile minimal in place of the final sh skips them and gives you only the compiler, the standard library and Cargo. That saves some download and a good deal of disk space, because the documentation is large once it is unpacked. You can add the rest later with rustup component add rust-docs clippy rustfmt.

On Windows, download and run rustup-init.exe from rust-lang.org/tools/install. It asks to install the Visual Studio C++ build tools if they are missing; accept, because Rust on Windows uses Microsoft's linker.

Check it worked

The installer ends with a line such as Rust is installed now. Great!, and ls ~/.cargo/bin lists cargo, rustc and rustup among other tools.

Troubleshooting

error: linker 'cc' not found the first time you build means the C build tools are missing. Install build-essential as above and build again.

Step 2 · Check rustc, cargo and rustup

Ask each tool for its version:

Bash
rustc --version
cargo --version
rustup --version
rustup show

rustup show lists the installed toolchains and marks the one in use. A toolchain is one complete set of rustc, Cargo and the standard library for one version. Rust releases a new stable version every six weeks, and rustup update moves you to it. rustup, not apt, keeps Rust up to date, so sudo apt upgrade never touches it.

Check it worked

rustc --version prints something like rustc 1.100.0 ( followed by a commit hash and date, and cargo --version prints a matching cargo 1.100.0. rustup show names a toolchain starting stable- or 1.100, followed by your platform, such as x86_64-unknown-linux-gnu.

Step 3 · Create a project with cargo new

Make a throwaway folder for this tutorial and ask Cargo for a new project called hello:

Bash
mkdir -p ~/rust-demo
cd ~/rust-demo
cargo new hello
cd hello
ls -a
cat Cargo.toml
cat src/main.rs

cargo new created a crate, Rust's word for one unit of compiled code: a program or a library. It also ran git init if Git is installed, which is why you see a .git folder and a .gitignore. Here is what each file is for.

Cargo.toml is the project's manifest, written in TOML (a simple key = value format):

TOML
[package]
name = "hello"
version = "0.1.0"
edition = "2024"

[dependencies]
  • name and version identify your crate.
  • edition picks a set of language rules. Editions let Rust change syntax every few years without breaking old code: a 2015-edition crate and a 2024-edition crate still compile together. Cargo writes the newest edition it knows, 2024 at the time of writing.
  • [dependencies] is empty for now. Library names and versions go here, and Cargo downloads them from crates.io when you build.

src/main.rs is the program itself:

Rust
fn main() {
    println!("Hello, world!");
}
  • fn main() declares a function called main, the place every Rust program starts. fn is how all functions begin. The empty brackets mean it takes no arguments, and with no return type written, it returns nothing.
  • The curly braces hold the function's body.
  • println! prints a line of text and a newline. The ! matters: it marks a macro, not a function. A macro is code that writes code during compilation. println! is a macro because it checks, at compile time, that the {} placeholders in the text match the values you pass, something an ordinary Rust function cannot do. Get the count wrong and the program does not compile, rather than printing nonsense at run time.
  • The semicolon ends the statement.

Check it worked

ls -a shows .git, .gitignore, Cargo.toml and src. cat src/main.rs prints the three-line program above, and Cargo.toml contains name = "hello".

Step 4 · Run it with cargo run

One command compiles the program and runs it:

Bash
cargo run
ls
cat Cargo.lock

cargo run prints two status lines first, Compiling hello v0.1.0 and something like `Finished `dev profile [unoptimized + debuginfo]`, then `Running with the program's path, and finally your program's output. Run it a second time and the Compiling line disappears: Cargo only rebuilds when a source file changes.

The build left two new things behind:

  • target/ holds everything Cargo compiled. It is safe to delete at any time (cargo clean does it for you), and .gitignore already keeps it out of Git.
  • Cargo.lock records the exact version of every dependency used in the build. You have none yet, so it lists only hello itself. Once you add crates it pins each one, so a teammate who builds next month gets the same versions you tested. Commit Cargo.lock for programs. Cargo.toml says what you are willing to accept; Cargo.lock says what you actually got.

Check it worked

The last line of cargo run output is Hello, world!. ls now shows Cargo.lock and target next to Cargo.toml and src, and Cargo.lock contains a [[package]] entry with name = "hello".

Step 5 · Compare a debug and a release build

cargo run and cargo build make a debug build: compiled quickly, with no optimisation, and with extra checks such as stopping the program if a number overflows. --release makes an optimised build, which takes longer to compile and runs faster. Build both and compare:

Bash
cargo build
cargo build --release
ls -l target/debug/hello target/release/hello
./target/release/hello

The second build prints something like `Finished `release profile [optimized]`. Each profile has its own folder under `target/, and each holds a standalone native program. You can run ./target/release/hello directly, with no Cargo and no Rust installed: copy it to another Linux machine with the same processor type and a similar or newer Linux distribution and it usually runs there too. It still relies on the system C library (glibc), so a much older distribution may refuse to run it.

For Hello World the speed difference cannot be measured; for real work, release builds are often many times faster. Use debug builds while you write code, because they compile faster and catch overflow, and --release for anything you time, ship or deploy. If you build on a low-end laptop, expect release builds of larger projects to take noticeably longer.

Check it worked

ls -l lists two files, target/debug/hello and target/release/hello, each with its own size in bytes; the debug one is usually larger because it carries debugging information. Running the release program prints Hello, world!.

Step 6 · Read a number and handle the Result

A program that only prints is half a program. This version asks for a whole number and doubles it. Reading input and turning text into a number can both fail, and Rust makes you decide what happens when they do. Replace src/main.rs:

Bash
cat > src/main.rs <<'RS'
use std::io;

fn main() {
    println!("Enter a whole number:");

    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => {}
        Err(error) => {
            println!("Could not read your input: {error}");
            return;
        }
    }

    let text = input.trim();
    match text.parse::<i32>() {
        Ok(number) => {
            let doubled = i64::from(number) * 2;
            println!("{number} doubled is {doubled}.");
        }
        Err(error) => println!("\"{text}\" is not a whole number: {error}"),
    }
}
RS
echo 21 | cargo run --quiet
echo ten | cargo run --quiet

Line by line:

  • use std::io; brings the standard library's input and output module into scope, so you can write io::stdin() instead of std::io::stdin().
  • let mut input = String::new(); creates an empty, growable piece of text. Variables in Rust cannot change unless you say so; mut says this one will, because read_line writes into it.
  • io::stdin().read_line(&mut input) reads one line from the keyboard, including the Enter key's newline. &mut input lends the variable to read_line with permission to change it, without giving it away.
  • read_line does not return the text. It returns a Result, a value that is either Ok (it worked, with the number of bytes read) or Err (it failed, with the reason). Rust has no exceptions; failure is an ordinary value that you have to deal with.
  • match looks at which one you got and runs the matching arm. Ok(_) => {} does nothing, because the text is already in input; the _ ignores the byte count. Err(error) prints the reason and return ends main early.
  • input.trim() removes the newline and any spaces around the text. Without it, "21\n" is not a number.
  • text.parse::<i32>() tries to turn the text into an i32, a 32-bit whole number. The ::<i32> part tells parse which type you want. It also returns a Result.
  • In the Ok(number) arm, i64::from(number) * 2 converts to a 64-bit number before doubling, so even the largest i32 cannot overflow.
  • {number} and {doubled} inside the text print those variables. \" puts a literal quote mark in the text.

Many examples online write .unwrap() instead of match. unwrap takes the value out of an Ok and stops the whole program with a panic message on an Err. It is fine in a quick experiment, but here typing ten would crash the program instead of explaining the problem. match makes you handle both cases, and the compiler checks you did not forget one.

The echo ... | lines feed the answer in for you, and --quiet hides Cargo's status lines. To type the number yourself, run cargo run on its own.

Check it worked

The first run prints Enter a whole number: and then 21 doubled is 42. The second prints "ten" is not a whole number: invalid digit found in string, and the program ends normally instead of crashing. Pressing Enter without typing anything prints a similar line ending cannot parse integer from empty string.

Troubleshooting

parse::<i32> accepts only the digits 0 to 9, with an optional + or - in front. Digits from other scripts, such as Arabic-Indic ٢١, and numbers with separators, such as 1,000, are rejected with invalid digit found in string. That is expected; accepting those needs extra code.

Step 7 · Read a compiler error

Rust's compiler, rustc, explains its errors in full sentences and often shows the fix. Make a second project with a deliberate mistake, a variable that is changed but not marked mut:

Bash
cd ~/rust-demo
cargo new broken
cd broken
cat > src/main.rs <<'RS'
use std::io;

fn main() {
    let input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => println!("You typed: {input}"),
        Err(error) => println!("Could not read your input: {error}"),
    }
}
RS
cargo build 2> errors.txt || echo "Build failed, as expected"
cat errors.txt

2> errors.txt saves the messages to a file so you can read them with cat; normally they appear straight in the terminal, in colour.

Read the message from the top:

  • The first line, error[E0596]: cannot borrow ` `input ` `as mutable, as it is not declared as mutable, says what is wrong. E0596 is an error code; rustc --explain E0596 prints a longer explanation with examples.
  • The --> line gives the file, line and column: src/main.rs:5: followed by a column number.
  • Below that, the compiler quotes your code and underlines the problem.
  • A help: line suggests the fix: consider changing this to be mutable, showing let mut input.

Fix it by adding mut after let, then build again:

Bash
cat > src/main.rs <<'RS'
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => println!("You typed: {input}"),
        Err(error) => println!("Could not read your input: {error}"),
    }
}
RS
echo hello | cargo run --quiet

Check it worked

The first build prints Build failed, as expected, and errors.txt contains error[E0596] with a help: line suggesting mut. After the fix, the program prints You typed: hello.

Common beginner mistakes

  • Writing println without the !. Rust then looks for a function called println, finds none, and the error tells you to add ! because a macro of that name exists.
  • Running rustc src/main.rs inside a Cargo project. It works for one file, but leaves the program in the current folder and ignores Cargo.toml and its dependencies. Use cargo run and cargo build.
  • Forgetting mut, as you just saw, or forgetting .trim() before parse, which makes every input fail.
  • Using .unwrap() everywhere and being surprised when the program panics on bad input.
  • Fighting the compiler. When it rejects code, read the help: line first; it is right far more often than not.

Step 8 · Know where Rust is used and how to clean up

Rust is used where speed and safety both matter:

  • Systems software and infrastructure: databases, network proxies, container tools and parts of cloud providers' services.
  • Command-line tools: ripgrep and many modern replacements for classic Unix tools are written in Rust, because Cargo builds one self-contained program per platform.
  • WebAssembly: Rust compiles to WebAssembly well, so the same code can run in a browser.
  • Browser engines: Firefox uses Rust components, such as its CSS engine.
  • Operating systems: the Linux kernel accepts drivers written in Rust alongside C.

When you are done, remove the tutorial folder:

Bash
cd ~
rm -rf ~/rust-demo

To update Rust when a new version comes out, run:

Bash
rustup update

To remove Rust completely, including rustup, every toolchain and the ~/.cargo and ~/.rustup folders, run:

Bash
rustup self uninstall

Check it worked

ls ~/rust-demo reports No such file or directory. rustc --version still prints rustc 1.100.0 or later, because removing a project does not touch the toolchain.

Next steps

  • Compare another compiled language that also ships its own build tool: Hello World in Go.
  • See the language Rust is most often compared with: Hello World in C++.
  • Try a newer systems language with a different approach to memory: Hello World in Zig.
  • Add a dependency: put rand = "0.10" under [dependencies] in Cargo.toml, run cargo build, and look at how Cargo.lock changes. The Rust book at doc.rust-lang.org/book builds a guessing game from exactly this starting point.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.