Create a new binary project using Cargo, add a main function to src/main.rs that prints "Hello, world!", and run it with cargo run. This single step handles compilation, linking, and execution automatically.
First, initialize a new project in your terminal. Cargo is Rust's package manager and build tool, and it sets up the correct directory structure for you.
cargo new hello_world
cd hello_world
This creates a src/main.rs file. Open it and replace the default content with the standard "Hello, world!" implementation. Rust requires the main function to be the entry point, and println! is a macro (notice the exclamation mark) used for printing to the standard output with a newline.
fn main() {
println!("Hello, world!");
}
To run the program, execute the following command from the project root:
cargo run
You should see Hello, world! printed to your terminal. Under the hood, cargo run compiles your code, checks for errors, links the binary, and executes it. If you want to build the binary without running it immediately, use cargo build, which places the executable in the target/debug directory.
A few key things to notice here:
- Ownership and Borrowing: Even in this simple program, Rust's compiler checks that you aren't violating memory safety rules, though you won't see that complexity yet.
- Macros vs. Functions:
println!is a macro, not a standard function. This allows it to accept a variable number of arguments and perform compile-time formatting checks. - No Semicolon on Blocks: The
mainfunction body is a block, so it doesn't end with a semicolon, but the statement inside (println!) does.
If you encounter an error like error[E0425]: cannot find function 'main' in the crate root, ensure your function is named exactly fn main() and is at the top level of src/main.rs. If the build fails due to missing dependencies, check your Cargo.toml, though "Hello, world!" requires no external crates.
Once you've run this, you have a working Rust environment. The next step is usually exploring variables, data types, or functions by modifying main.rs and running cargo run again to see the immediate feedback loop in action.