Rust Hello World
To get started with Rust and create a "Hello, World!" program, follow these steps:
Step 1: Install Rust
First, you need to install Rust. The recommended way to do this is by using rustup
, a tool for
managing Rust versions and associated tools:
- Open your terminal.
- Run the following command:
shcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Follow the on-screen instructions to complete the installation. After installation, make sure your
PATH
environment variable is updated. You can do this by restarting your terminal or running the
following command:
shsource $HOME/.cargo/env
Step 2: Create a New Rust Project
Create a new directory for your project and navigate into it. Then, use cargo
(Rust's package
manager and build system) to create a new project:
shcargo new hello_world
cd hello_world
This creates a new directory named hello_world
with the following structure:
csshello_world/
├── Cargo.toml
└── src
└── main.rs
Step 3: Write the "Hello, World!" Program
Open the src/main.rs
file in your preferred text editor and add the following code:
rustfn main() {
println!("Hello, world!");
}
Step 4: Build and Run the Program
To build and run your program, use the following cargo
commands:
shcargo build # This compiles your program
cargo run # This compiles and runs your program
When you run cargo run
, you should see the output:
Hello, world!
Full Example
Here's a complete example showing the contents of the main.rs
file:
rust// src/main.rs
fn main() {
println!("Hello, world!");
}
Explanation
fn main() { ... }
: This defines the main function, which is the entry point of the program.println!("Hello, world!");
: This prints "Hello, world!" to the console. Theprintln!
macro is used for printing text.
Additional Tips
- Documentation: Rust has excellent documentation. You can refer to the Rust Book for a comprehensive guide.
- Cargo: Cargo is a powerful tool that manages Rust projects, dependencies, and builds. You can learn more about it in the Cargo Book.
- Community: The Rust community is very welcoming. You can find help and resources on the Rust Users Forum, Rust subreddit, and Rust Discord.
That's it! You've successfully written and run your first Rust program.