In this section, we will write our first Rust program: the classic "Hello, World!" This simple program will help you understand the basic structure of a Rust program and how to compile and run it.
Writing the Program
-
Create a New Rust Project: Open your terminal and create a new Rust project using Cargo, Rust's package manager and build system.
cargo new hello_world cd hello_world
This command creates a new directory called
hello_world
with the following structure:hello_world ├── Cargo.toml └── src └── main.rs
-
Open the
main.rs
File: Navigate to thesrc
directory and open themain.rs
file in your favorite text editor. This file is where you will write your Rust code. -
Write the Code: Replace the contents of
main.rs
with the following code:fn main() { println!("Hello, world!"); }
Explanation:
fn main() { ... }
: This defines the main function, which is the entry point of every Rust program.println!("Hello, world!");
: This line prints the string "Hello, world!" to the console. Theprintln!
macro is used for printing text to the standard output.
Compiling and Running the Program
-
Compile the Program: In your terminal, make sure you are in the
hello_world
directory and run:cargo build
This command compiles your program and creates an executable file in the
target/debug
directory. -
Run the Program: To run the compiled program, use the following command:
cargo run
You should see the following output:
Hello, world!
Practical Exercise
Task:
Create a new Rust project and modify the main.rs
file to print a custom message of your choice.
Steps:
- Create a new Rust project named
custom_message
. - Open the
main.rs
file in thesrc
directory. - Replace the contents of
main.rs
with code that prints a custom message. - Compile and run the program to see your custom message.
Solution:
-
Create the Project:
cargo new custom_message cd custom_message
-
Modify
main.rs
:fn main() { println!("Welcome to Rust programming!"); }
-
Compile and Run:
cargo run
Expected output:
Welcome to Rust programming!
Common Mistakes and Tips
- Missing Semicolon: Ensure that each statement ends with a semicolon (
;
). For example,println!("Hello, world!")
should beprintln!("Hello, world!");
. - Correct Syntax for
println!
: Theprintln!
macro requires an exclamation mark (!
). Forgetting this will result in a compilation error. - File Structure: Make sure you are in the correct directory when running
cargo build
orcargo run
. These commands should be executed in the root directory of your project (e.g.,hello_world
).
Conclusion
In this section, you learned how to write, compile, and run a simple Rust program. You also learned about the basic structure of a Rust program and how to use the println!
macro to print text to the console. This foundational knowledge will be essential as you progress through more complex Rust programs. Next, we will dive into Rust's basic syntax and structure to build on what you've learned here.