Rust syntax
Created By: chatGPT
Rust is a system programming language that is designed for performance and safety. It emphasizes concurrency and memory safety, which eliminates many common bugs. Let's explore some of the basic syntax.
To define a variable in Rust, use the
let
keyword. By default, variables are immutable, but you can make them mutable by using mut
.let x = 5;
let mut y = 10;
You can create functions using the
fn
keyword. Functions can take parameters and return values.fn add(a: i32, b: i32) -> i32 {
a + b
}
Control flow in Rust is managed using if statements and loops like loop, while, and for. Here's an example of a simple conditional statement.
let number = 5;
if number < 10 {
println!("Number is less than 10");
} else {
println!("Number is 10 or more");
}
For loops can iterate over ranges or collections. The example below demonstrates a for loop iterating over a range.
for i in 0..5 {
println!("Number: {}", i);
}
Rust supports pattern matching with the
match
statement, which is a powerful control structure that can match values against patterns.let number = 1;
match number {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}
Structs are used to create custom data types in Rust. You can define a struct using the
struct
keyword.struct Person {
name: String,
age: u32,
}
let person = Person {
name: String::from("Alice"),
age: 30,
};
Implementing methods for structs is done with the
impl
keyword. Here's how it looks.impl Person {
fn greet(&self) {
println!("Hello, my name is {}.", self.name);
}
}
person.greet();
Error handling in Rust can be managed using
Result
and Option
types. Using pattern matching with these types helps to handle potential errors safely.fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(a / b)
}
}
match divide(10.0, 0.0) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}