As a C++ developer, you'll find Rust to be a familiar yet distinct language. Rust prioritizes memory safety, performance, and concurrency, making it an attractive choice for systems programming.
Key Language Features
Here are some key features of Rust, along with examples:
1. Ownership and Borrowing
Rust's ownership system ensures memory safety by enforcing the following rules:
Each value has an owner that is responsible for deallocating it.
There can be only one owner at a time.
When the owner goes out of scope, the value is deallocated.
rust
fn main() {
let s = String::from("hello"); // s is the owner of the string
let len = calculate_length(&s); // borrowing s
println!("The length of '{}' is {}.", s, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
2. References and Mutability
Rust allows you to create references to values, which are essentially pointers to the value. You can also specify whether a reference is mutable or immutable.
Rust provides a strong focus on error handling through the use of Result and Option types.
rust
fn main() {
let result = divide(10, 2);
match result {
Ok(value) => println!("Result: {}", value),
Err(error) => println!("Error: {}", error),
}
}
fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
if b == 0 {
Err("Cannot divide by zero!")
} else {
Ok(a / b)
}
}
4. Pattern Matching
Rust's pattern matching allows you to specify multiple alternatives and execute different code for each one.
rust
fn main() {
let number = 1;
match number {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Something else"),
}
}
5. Closures
Rust's closures are functions that can capture their environment and be used as higher-order functions.
rust
fn main() {
let add_one = |x: i32| x + 1;
println!("{}", add_one(5));
}
6. Enums
Rust's enums allow you to define a set of named values.
rust
enum Color {
Red,
Green,
Blue,
}
fn main() {
let color = Color::Green;
match color {
Color::Red => println!("Red"),
Color::Green => println!("Green"),
Color::Blue => println!("Blue"),
}
}
7. Structs
Rust's structs allow you to define composite data types.
rust
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: String::from("John"),
age: 30,
};
println!("Name: {}, Age: {}", person.name, person.age);
}
Conclusion
Rust offers a unique set of features that prioritize memory safety, performance, and concurrency. Its ownership system, references, and error handling mechanisms make it an attractive choice for systems programming. With its strong focus on safety and performance, Rust is an excellent language to learn for any C++ developer looking to expand their skillset.