Rust Syntax: A Comprehensive Guide
Learn Rust through interactive, bite-sized lessons. Master memory safety without garbage collection.
Start Rust Journey →Rust syntax forms the foundation of writing efficient and safe code in the Rust programming language. This guide will walk you through the essential elements of Rust's syntax, enabling you to start writing robust programs.
Basic Structure
Rust programs typically begin with a main() function, which serves as the entry point:
fn main() {
// Your code here
}
Variables and Data Types
In Rust, variables are immutable by default. Use the let keyword to declare variables:
let x = 5; // Immutable
let mut y = 10; // Mutable
Rust is statically typed, but it can infer types. You can also explicitly declare types:
let z: i32 = 15; // Explicitly typed integer
For more details on variables and data types, check out the Rust Variables and Rust Data Types guides.
Functions
Functions in Rust are declared using the fn keyword:
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
This function takes a string slice as an argument and returns a String. Learn more about functions in the Rust Functions guide.
Control Flow
Rust provides familiar control flow constructs:
If-Else Statements
let number = 7;
if number < 5 {
println!("Number is less than 5");
} else if number == 5 {
println!("Number is 5");
} else {
println!("Number is greater than 5");
}
Loops
Rust offers several types of loops:
// Infinite loop
loop {
println!("This will run forever");
break; // Use break to exit the loop
}
// While loop
let mut count = 0;
while count < 5 {
println!("Count: {}", count);
count += 1;
}
// For loop
for i in 0..5 {
println!("Index: {}", i);
}
For more on control flow, visit the Rust Control Flow page.
Comments
Rust supports both single-line and multi-line comments:
// This is a single-line comment
/*
This is a
multi-line comment
*/
/// This is a documentation comment
Ownership and Borrowing
Rust's unique feature is its ownership system, which ensures memory safety without a garbage collector:
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2, s1 is no longer valid
let s3 = String::from("world");
let len = calculate_length(&s3); // s3 is borrowed
Understanding ownership is crucial in Rust. Dive deeper with the Rust Ownership Concept and Rust Borrowing Rules guides.
Error Handling
Rust encourages explicit error handling using the Result enum:
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {:?}", error),
};
}
For more on error handling, check out the Rust Result guide.
Best Practices
- Use meaningful variable and function names
- Leverage Rust's type system for safer code
- Handle errors explicitly using
Result - Follow the ownership rules to prevent memory issues
- Use
cargo fmtto maintain consistent code style
Mastering Rust syntax is the first step towards becoming a proficient Rust developer. As you progress, explore advanced topics like Rust Traits, Rust Generics, and Rust Concurrency to unlock the full potential of this powerful language.