Rust, a modern system programming language, focuses on performance, safety, and concurrency. But before delving into its powerful features, it’s crucial to understand the basics of Rust’s syntax and structure. This article will guide you through the foundational elements of the Rust programming language.
Basic Syntax
Rust’s syntax might seem familiar if you’ve used other C-style syntax languages. Let’s start with a simple “Hello, World!” program:
fn main() {
println!("Hello, World!");
}
In the example above, fn main()
defines the main function, where the execution of the Rust program starts. println!
is a macro that prints text to the console.
Variables and Mutability
In Rust, variables are immutable by default. If you want to declare a mutable variable, you need to use the mut
keyword:
let x = 5;
let mut y = 6;
y = 7; // This is allowed
x = 8; // This will cause a compile-time error
Data Types
Rust is a statically typed language, meaning it must know the types of all variables at compile time. The scalar types in Rust include integers, floating-point numbers, Booleans, and characters.
let x: i32 = 5; // integer
let y: f64 = 6.7; // floating point number
let b: bool = true; // boolean
let c: char = 'z'; // character
Control Flow
Rust has three types of control flow: if
expressions, loop
expressions, and match
expressions.
// If expression
let number = 6;
if number % 2 == 0 {
println!("number is even");
} else {
println!("number is odd");
}
// Loop expression
let mut count = 0;
loop {
println!("count: {}", count);
count += 1;
if count > 5 {
break;
}
}
// Match expression
let coin = "Penny";
let value = match coin {
"Penny" => 1,
"Nickel" => 5,
"Dime" => 10,
"Quarter" => 25,
_ => 0,
};
println!("Coin value: {}", value);
Functions
Functions are declared using the fn
keyword. They can also have parameters and return values.
fn add_two_numbers(x: i32, y: i32) -> i32 {
x + y
}
fn main() {
let sum = add_two_numbers(5, 6);
println!("Sum: {}", sum);
}
Conclusion
Rust’s syntax and structure play a crucial role in the language’s safety, performance, and concurrency. Understanding these basics will make it easier for you to explore Rust’s advanced features. Remember, practice is key to mastering Rust. Happy coding!