Rust: Basic Syntax
Rust is a systems programming language known for its performance, reliability, and memory safety. Understanding the basic syntax of Rust is essential for writing efficient and safe code. Let's dive into some key syntax elements in Rust.
Variables and Data Types
In Rust, variables are immutable by default. To create a mutable variable, use the let mut
keyword.
fn main() {
let x = 10; // immutable variable
let mut y = 20; // mutable variable
println!("x: {}", x);
println!("y: {}", y);
}
Output:
x: 10
y: 20
Functions
Functions in Rust are defined using the fn
keyword. Rust functions can return values using the ->
syntax.
fn add(a: i32, b: i32) -> i32 {
return a + b;
}
fn main() {
let result = add(5, 3);
println!("Result: {}", result);
}
Output:
Result: 8
Control Flow
Rust supports common control flow statements like if
, while
, and for
loops.
fn main() {
let number = 5;
if number % 2 == 0 {
println!("Even");
} else {
println!("Odd");
}
for i in 0..5 {
println!("Iteration: {}", i);
}
}
Output:
Odd
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Use Cases
Rust's powerful syntax makes it ideal for systems programming, web development, and embedded systems. Its memory safety features make it a popular choice for building high-performance applications.
Interview Importance
Knowledge of Rust syntax is crucial for technical interviews in software development roles. Demonstrating proficiency in Rust can set you apart from other candidates and showcase your ability to write efficient and safe code.
Conclusion
Mastering the basic syntax of Rust is essential for writing efficient and safe code. By understanding variables, functions, control flow, and use cases, you can leverage Rust's capabilities to build high-performance applications.