BudiBadu Logo
Samplebadu

Rust by Example: Hello World

Rust 1.75+

Your first Rust program - the traditional starting point for learning any programming language. This code sample demonstrates the basic structure of a Rust application, including the main function entry point and the println! macro for output.

Code

fn main() {
    // This is a comment
    // The main function is the entry point of the program
    
    // println! is a macro that prints text to the console
    println!("Hello, World!");
    
    // Formatting output
    let name = "Rustacean";
    println!("Hello, {}!", name);
}

Explanation

The "Hello, World!" program is the traditional starting point for learning any new programming language. In Rust, it serves to introduce the fundamental structure of a program: the main function. Just like in C, C++, or Java, main is the entry point where execution begins. Rust uses curly braces {} to define code blocks and semicolons ; to terminate statements.

One distinct feature you'll notice immediately is the exclamation mark in println!. This indicates that println! is not a regular function, but a macro. Macros in Rust are powerful metaprogramming tools that generate code at compile time. In this case, the macro handles type checking and formatting of the arguments before the program even runs, ensuring safety and correctness.

Under the hood, println! locks the standard output (stdout) for the current thread to ensure that output doesn't get interleaved with other threads. It is also line-buffered when connected to a terminal, meaning it flushes the buffer immediately upon encountering a newline character. For high-performance I/O scenarios where you are printing thousands of lines, you might want to manually lock stdout or use a BufWriter to avoid the overhead of repeated locking and flushing.

We also see a glimpse of variable binding with let name = "Rustacean";. Rust is a statically typed language, but it has powerful type inference, so we didn't need to explicitly say that name is a string. The {} syntax inside the print string is a placeholder, similar to %s in C or {} in Python's format, allowing us to inject values directly into the output string.

Code Breakdown

1
fn main() { ... } defines the main function. The keyword fn is used to declare functions. This is where your program starts executing.
6
println!("Hello, World!"); calls the print line macro. The ! distinguishes it from a function call. It expands to code that writes to stdout and appends a newline.
9-10
let name = ... creates a variable. println!("Hello, {}!", name); uses a placeholder {} to insert the value of name into the string. This is the standard way to format output in Rust.