RustArena

Hello World in Rust: fn main, println! and Cargo

Write and run your first Rust program with Cargo, and learn what fn main, println! and the exclamation mark mean.

Every Rust program starts running at a function called main. The smallest useful program prints one line:

fn main() {
    println!("Hello, world!");
}
Hello, world!

Line by line:

Running it with Cargo

Cargo is Rust's build tool and package manager. It comes with Rust when you install it with rustup (from rustup.rs). To create a project and run it:

$ cargo new hello
$ cd hello
$ cargo run
   Compiling hello v0.1.0 (/home/you/hello)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
     Running `target/debug/hello`
Hello, world!

cargo new creates Cargo.toml (the project's name, version and dependencies) and src/main.rs, which already contains the program above. The commands you'll use every day:

Command What it does
cargo run compile if needed, then run
cargo build compile into target/debug/
cargo check type-check without building a program (the fastest feedback)
cargo build --release compile with optimizations, for real speed
cargo fmt format your code in the standard style
cargo clippy lint: point out bugs and less idiomatic code
cargo test run the tests

print!, escapes and braces

print! is println! without the newline. Inside a string, \n is a newline, \t a tab, \" a double quote and \\ a backslash. Curly braces are placeholders ({} is replaced by the next argument), so a literal brace is written twice: {{ and }}.

Common mistakes

Forgetting the ! makes Rust look for a function called println, which doesn't exist:

fn main() {
    println("Hello");
}
error[E0423]: cannot find function `println` in this scope
 --> src/main.rs:2:5
  |
2 |     println("Hello");
  |     ^^^^^^^ not found in this scope
  |
  = note: a macro named `println` exists in another namespace
help: use `!` to invoke the macro
  |
2 |     println!("Hello");
  |            +

Using single quotes for text is the other classic. In Rust 'a' is one character (a char); text always uses double quotes:

fn main() {
    println!('Hello');
}
error: character literal may only contain one codepoint

Read compiler errors from the top. The first error is usually the real problem, and rustc often prints the fix in a help: line, as above. On this site you can edit and run every example; the playground shows the same errors cargo run would.

Example

fn main() {
    println!("Hello, world!");
    print!("Rust ");
    print!("is ");
    println!("ready.");
    println!("Tabs:\tone\ttwo");
    println!("Braces {{}} and a \"quote\"");
    println!("{} + {} = {}", 2, 3, 2 + 3);
}

Output:

Hello, world!
Rust is ready.
Tabs:	one	two
Braces {} and a "quote"
2 + 3 = 5

Practice it