Simple hello world program using rust
Writing a "Hello, World!" program in Rust is a great way to get started with the language. Here’s a step-by-step guide on how to write and run a simple Rust program that prints "Hello, World!" to the console.
Step 1: Set Up Your Environment
Before you write the code, ensure that Rust is installed on your machine. If not, follow the installation instructions for your operating system as detailed previously.
Step 2: Create a New Rust Project
Rust uses a build system and package manager called Cargo. To create a new Rust project, use Cargo to set up your project structure.
- Open a terminal or command prompt.
- Run the following command to create a new Rust project:
cargo new hello_world
- Navigate to the newly created project directory:
cd hello_world
Step 3: Write the Code
In the src
directory of your project, you will find a file named main.rs
. Open this file in your favorite text editor or integrated development environment (IDE) and add the following code:
fn main() {
println!("Hello, World!");
}
Step 4: Build and Run the Project
To compile and run your "Hello, World!" program, use Cargo:
- In the terminal, make sure you are in the root directory of your project (where the
Cargo.toml
file is located). - Run the following command to compile and run your project:
cargo run
You should see the following output in the terminal:
Compiling hello_world v0.1.0 (path_to_your_project)
Finished dev [unoptimized + debuginfo] target(s) in 2.34s
Running `target/debug/hello_world`
Hello, World!
Explanation of the Code
fn main() { ... }
: This defines the main function, which is the entry point of a Rust program. Themain
function is where the execution of the program begins.println!("Hello, World!");
: This line prints the string "Hello, World!" to the console. Theprintln!
macro is used for printing text to the standard output.