When learning any programming language, it usually starts with writing a simple Hello, World! program. In Rust, this is very simple and can be done with just a few lines of code.
fn main() {
println!("Hello, World!");
}
This code defines a function named main, which is the entry point of a Rust program. Inside the function body, the println! macro is used to output a string to the console.
Writing and Running the Hello World Program
Creating a new Rust project is the best way to run a Hello, World! program. Using cargo makes it easy to manage projects. First, create a new project:
cargo new hello_world
cd hello_world
This generates a folder named hello_world in the current directory, containing the basic project structure. Open the src/main.rs file, and you will see the default Hello, World! code:
fn main() {
println!("Hello, world!");
}
To run the program, execute in the project directory:
cargo run
# Output: Hello, world!
Code Analysis
Let's analyze the key parts of the Hello, World! program in detail:
fn main(): Defines a function,fnis a keyword, andmainis the function name. In Rust, themainfunction is the starting point of the program.println!("Hello, World!"): This is a macro call used to print text to standard output. Macros end with!, which is different from regular functions.
You can modify the string to output different messages, for example:
fn main() {
println!("Welcome to Rust programming!");
}
Common Issues and Debugging
When writing Rust programs, you may encounter some common errors. For example, if you forget a semicolon, the compiler will report an error:
fn main() {
println!("Hello, World!") // Missing semicolon
}
Running cargo check can quickly check for syntax errors in the code without actually compiling:
cargo check
If the compilation is successful but the output does not meet expectations, use cargo build to compile the project, then manually run the executable file:
cargo build
./target/debug/hello_world
Hello, world!