Rust Syntax
Rust is a systems programming language that is known for its safety and performance. Here's a quick overview of its syntax:
Basic Structure
rustfn main() {
println!("Hello, world!");
}
Variables and Mutability
By default, variables are immutable.
rustfn main() {
let x = 5; // immutable
let mut y = 10; // mutable
y = 15;
println!("x: {}, y: {}", x, y);
}
Data Types
Rust is statically typed, so types must be known at compile time.
rustfn main() {
let integer: i32 = 42;
let floating_point: f64 = 3.14;
let boolean: bool = true;
let character: char = 'R';
let string: &str = "Rust";
println!("{} {} {} {} {}", integer, floating_point, boolean, character, string);
}
Functions
Functions in Rust are declared with fn
keyword.
rustfn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let sum = add(5, 10);
println!("Sum: {}", sum);
}
Control Flow
Rust supports usual control flow structures like if, else, and loops.
rustfn main() {
let number = 6;
if number % 2 == 0 {
println!("The number is even.");
} else {
println!("The number is odd.");
}
// Loop
for i in 0..5 {
println!("i: {}", i);
}
}
Ownership and Borrowing
Rust has a unique ownership system to manage memory safety without a garbage collector.
rustfn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // This would cause a compile-time error
let s3 = s2.clone(); // Explicitly clone s2 to s3
println!("{}", s2); // Now s2 can still be used
}
Structs
Structs are used to create custom data types.
ruststruct User {
username: String,
email: String,
active: bool,
}
fn main() {
let user1 = User {
username: String::from("user1"),
email: String::from("user1@example.com"),
active: true,
};
println!("Username: {}", user1.username);
}
Enums
Enums are used to define a type that can be one of several variants.
rustenum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
fn main() {
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
println!("Home: {:?}", home.kind);
println!("Loopback: {:?}", loopback.kind);
}
Pattern Matching
Rust's match statement is a powerful control flow operator.
rustenum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {
let coin = Coin::Dime;
println!("Value: {} cents", value_in_cents(coin));
}
These are just a few highlights of Rust's syntax. The language has many more features, such as traits, generics, and concurrency, which make it powerful and flexible for system-level programming.