Rust Beginner GuideHello WorldRustSyntax

Article & Tutorial

Rust Syntax and Hello World: Complete Beginner Guide with Examples

Learn Rust syntax from the ground up with Hello World, main(), println!, comments, statements, expressions, blocks, macros, formatting, Cargo commands, compiler errors, and hands-on examples.

Rust Syntax and Hello World: Complete Beginner Guide with Examples article illustration
Rust Syntax and Hello World: Complete Beginner Guide with Examples article illustration
Contents

Rust Syntax and Hello World

Learn how a Rust program is structured and understand the syntax you will see in every Rust project: fn main(), statements, expressions, blocks, comments, macros, formatting and compiler feedback.

What you will learn

  • How Rust source files are structured
  • What fn main() means
  • How println! and other macros work
  • Statements versus expressions
  • Semicolons and return values
  • Code blocks and scope
  • Comments and documentation comments
  • String formatting and placeholders
  • How to compile and run syntax examples
  • How to read basic compiler errors

1. Create a Rust project

bash
cargo new rust_syntax_lab cd rust_syntax_lab cargo run

Cargo creates a package containing a Cargo.toml manifest and a src/main.rs source file. A new binary project starts with a minimal Hello World application.

2. Your first Rust program

bash
fn main() { println!("Hello, world!"); }

Run it:

bash
cargo run

Expected output:

bash
Hello, world!

3. Understanding fn main()

Every normal Rust binary has an entry point named main. Execution begins there.

bash
fn main() { // program starts here }
SyntaxMeaning
fnDeclares a function.
mainThe entry-point function for a binary program.
()The function takes no parameters.
{ ... }The function body is a code block.

Rust convention uses snake_case for function and variable names:

bash
fn calculate_total() { println!("Calculating..."); }

4. What is println! ?

println! prints formatted text followed by a newline.

bash
println!("Welcome to Rust!");

The exclamation mark is important: println! is a macro, not an ordinary function call. Rust macros can accept syntax that ordinary functions cannot and are expanded by the compiler.

println!

Prints text and adds a newline.

bash
println!("Hello");

print!

Prints without automatically adding a newline.

bash
print!("Hello "); print!("Rust");

eprintln!

Prints to standard error, useful for errors and diagnostics.

bash
eprintln!("Something went wrong");

5. Formatting output

Rust formatting macros support placeholders.

bash
fn main() { let language = "Rust"; let year = 2015; println!("I am learning {language}."); println!("Rust 1.0 was released in {year}."); }

You can also use positional placeholders:

bash
println!("{} + {} = {}", 10, 20, 30);

Named formatting can make complex messages clearer:

bash
println!( "User {name} completed chapter {chapter}", name = "Alex", chapter = 2 );

Debug formatting

bash
let ports = [80, 443, 8080]; println!("{:?}", ports);

Pretty debug formatting:

bash
println!("{:#?}", ports);

6. Statements and expressions

This distinction is one of the most important parts of Rust syntax.

Statements

A statement performs an action and normally does not produce a value that can be used by the surrounding expression.

bash
let x = 10; let y = 20;

Expressions

Expressions evaluate to a value:

bash
5 + 5 x * 2 { let value = 4; value + 1 }

A block can therefore produce a value:

bash
fn main() { let answer = { let x = 20; x + 22 }; println!("Answer: {answer}"); }

The last line x + 22 has no semicolon. It becomes the block's resulting value.

7. Why semicolons matter

bash
fn add_one(x: i32) -> i32 { x + 1 }

The final expression returns the value automatically. This is valid Rust.

This version is different:

bash
fn add_one(x: i32) -> i32 { x + 1; }

The semicolon suppresses the expression value, so the compiler reports a type mismatch because the function promises to return i32.

8. Code blocks and scope

Curly braces create blocks. Variables declared in a block normally live only inside that scope.

bash
fn main() { let outside = 10; { let inside = 20; println!("outside={outside}, inside={inside}"); } println!("outside={outside}"); // println!("{inside}"); // compiler error }

9. Comments in Rust

Single-line comment

bash
// This is a comment println!("Hello");

Multiple lines

bash
// First line // Second line // Third line

Block comments

bash
/* This is a block comment. It can span multiple lines. */

Documentation comments

Rust also has documentation comments that can become generated API documentation:

bash
/// Adds two integer values. fn add(a: i32, b: i32) -> i32 { a + b }

Generate project documentation with:

bash
cargo doc --open

10. Basic naming conventions

ItemCommon Rust styleExample
Variablessnake_caseuser_name
Functionssnake_casecalculate_total
Types / structs / enumsUpperCamelCaseUserProfile
ConstantsSCREAMING_SNAKE_CASEMAX_RETRIES

11. A complete syntax example

bash
fn greeting(name: &str) -> String { format!("Hello, {name}!") } fn main() { let user = "Kaushik"; let message = greeting(user); println!("{message}"); let result = { let a = 10; let b = 20; a + b }; println!("Calculation result: {result}"); }

Run:

bash
cargo run

Expected:

bash
Hello, Kaushik! Calculation result: 30

12. Compile without running

bash
cargo build

For faster compile-time feedback while developing:

bash
cargo check

cargo check is useful when you want Rust's compiler diagnostics without producing the final executable.

13. Read compiler errors instead of fighting them

Rust compiler diagnostics frequently show the file, line, problematic code and a suggested correction.

Try this intentionally broken example:

bash
fn main() { println!("Hello") println!("Rust"); }

The missing semicolon between macro invocations causes a compile error. Run:

bash
cargo check

Then read the diagnostic from top to bottom. During Rust learning, compiler messages are effectively an interactive tutor.

14. Formatting Rust code automatically

Instead of manually aligning code, use Rust's formatter:

bash
cargo fmt

Check formatting without changing files:

bash
cargo fmt --check

15. Lint your code with Clippy

bash
cargo clippy

Clippy provides additional recommendations for correctness, readability and idiomatic Rust.

16. Mini lab

Create this program without copying the final answer first:

  1. Create a project named chapter2_lab .
  2. Store your name and a technology in variables.
  3. Print both values using captured formatting.
  4. Create an inner block that calculates 15 * 4 .
  5. Assign the result of that block to a variable.
  6. Print the result.
  7. Add a documentation comment above a helper function.
  8. Run cargo fmt , cargo check , cargo clippy and cargo run .

Example solution

bash
/// Creates a short learning message. fn learning_message(name: &str, technology: &str) -> String { format!("{name} is learning {technology}") } fn main() { let name = "Kaushik"; let technology = "Rust"; println!("{}", learning_message(name, technology)); let result = { let value = 15; value * 4 }; println!("15 × 4 = {result}"); }

17. Common beginner mistakes

MistakeFix
Writing println()Use the macro syntax println!() .
Forgetting semicolons between statementsAdd ; where the statement should end.
Adding a semicolon to a return expressionRemove it when the final expression should provide a function/block value.
Using a variable outside its scopeMove the declaration to a wider scope or restructure the code.
Ignoring compiler outputRead the first compiler error carefully before addressing later cascading errors.

18. Recommended workflow for every example

bash
cargo fmt cargo check cargo clippy cargo test cargo run

Rust syntax cheat sheet

bash
// Function fn greet() { println!("Hello!"); } // Variable let name = "Rust"; // Code block returning a value let x = { let y = 5; y + 1 }; // Function returning a value fn double(value: i32) -> i32 { value * 2 } // Comment // one line // Documentation comment /// Documents the next item.

Official references

This chapter follows the current Rust language and Cargo documentation. Rust's official book introduces variables, data types, functions, comments and control flow as common programming concepts, while Cargo provides the standard package/build workflow.

  • The Rust Programming Language — Common Programming Concepts
  • The Rust Programming Language — Functions
  • The Cargo Book — First Steps with Cargo

Did this help?

Yes No

Join the discussion

0 Comments

Ask questions, add context, or share what worked.

Sign in to join the discussion

No comments yet. Start the discussion.

More from Melochip Editorial

Related articles

Stay in the loop. Get new Melochip articles

Receive Melochip article updates when new articles are available. Explicit opt-in only.

No pre-checked boxes. Unsubscribe support is part of the subscriber foundation.