目录高级特性Rust的安全性高级trait高级类型高级函数和闭包宏高级特性Rust的安全性内存安全Rust通过所有权、借用和生命周期机制确保内存安全。所有权每个值都有一个所有者,当所有者离开作用域时,该值会被自动释放。fnmain(){le
内存安全 Rust 通过所有权、借用和生命周期机制确保内存安全。
所有权
fn main() {
let s = String::from("hello"); // s 是所有者
{
let r = &s; // r 是借用
} // r 离开作用域,借用结束
println!("{}", s); // s 仍然有效
}
借用规则
fn main() {
let mut s = String::from("hello");
{
let r1 = &s; // 不可变借用
let r2 = &s; // 可以存在多个不可变借用
println!("{} and {}", r1, r2);
}
let r3 = &mut s; // 可变借用
println!("{}", r3);
}
生命周期
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string is long");
let result = longest(string1.as_str(), "xyz");
println!("The longest string is {}", result);
}
并发安全
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
let counter = Mutex::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
泛型 Trait 允许为不同类型定义通用行为。
trait Displayable {
fn display(&self);
}
impl Displayable for i32 {
fn display(&self) {
println!("Integer: {}", self);
}
}
impl Displayable for String {
fn display(&self) {
println!("String: {}", self);
}
}
fn main() {
let number = 42;
let message = String::from("Hello, world!");
number.display();
message.display();
}
高级 Trait Bound 限制泛型参数的类型约束。
trait Summary {
fn summarize(&self) -> String;
}
impl Summary for String {
fn summarize(&self) -> String {
format!("Summary: {}", self)
}
}
fn print_summary<T: Summary>(item: T) {
println!("Summary: {}", item.summarize());
}
fn main() {
let message = String::from("Hello, world!");
print_summary(message);
}
默认方法 为 Trait 实现默认方法。
trait Greeting {
fn greet(&self) -> String;
fn default_greet(&self) -> String {
format!("Hello, {}", self)
}
}
impl Greeting for String {
fn greet(&self) -> String {
format!("Greeting: {}", self)
}
}
fn main() {
let name = String::from("Alice");
println!("{}", name.greet()); // 调用自定义方法
println!("{}", name.default_greet()); // 调用默认方法
}
智能指针 智能指针具有额外的行为,例如生命周期管理和所有权转移。
use std::rc::Rc;
use std::cell::RefCell;
struct Node {
value: i32,
next: Option<Rc<RefCell<Node>>>,
}
impl Node {
fn new(value: i32) -> Rc<RefCell<Node>> {
Rc::new(RefCell::new(Node { value, next: None }))
}
}
fn main() {
let a = Node::new(1);
let b = Node::new(2);
let c = Node::new(3);
a.borrow_mut().next = Some(b.clone());
b.borrow_mut().next = Some(c.clone());
println!("a -> {}", a.borrow().next.as_ref().unwrap().borrow().value);
println!("b -> {}", b.borrow().next.as_ref().unwrap().borrow().value);
}
Box 和 Rc 动态分配内存的对象。
fn main() {
let boxed_int = Box::new(42);
println!("Boxed int: {}", *boxed_int);
let shared_int = Rc::new(42);
let cloned_int = Rc::clone(&shared_int);
println!("Shared int: {}", *shared_int);
println!("Cloned int: {}", *cloned_int);
}
高阶函数 接受函数作为参数或返回函数的函数。
fn apply<F, T>(func: F, arg: T) -> T
where
F: Fn(T) -> T,
{
func(arg)
}
fn main() {
let result = apply(|x| x + 1, 5);
println!("Result: {}", result);
}
闭包 捕获外部作用域变量的匿名函数。
fn main() {
let x = 42;
let closure = |y| x + y;
println!("Closure result: {}", closure(5));
}
捕获规则 闭包可以捕获外部作用域的变量。
fn main() {
let x = 42;
let closure = move || x; // 捕获 x 并移动
println!("Closure result: {}", closure());
}
简单宏
使用 macro_rules!
定义简单的宏。
macro_rules! say_hello {
() => {
println!("Hello!");
};
}
fn main() {
say_hello!();
}
过程宏
使用 proc-macro
属性定义更复杂的宏。
// hello_macro.rs
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
#[proc_macro_attribute]
pub fn hello(attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as ItemFn);
let name = &input.sig.ident;
let expanded = quote! {
#input
fn #name() {
println!("Hello from {}", stringify!(#name));
}
};
proc_macro::TokenStream::from(expanded)
}
// main.rs
use hello_macro::hello;
#[hello]
fn hello_world() {
println!("Hello, world!");
}
fn main() {
hello_world();
}
设置环境 安装必要的依赖库。
cargo new concurrent_cache
cd concurrent_cache
cargo add parking_lot
编写缓存代码 创建一个并发安全的缓存。
use parking_lot::RwLock;
use std::collections::HashMap;
type CacheKey = String;
type CacheValue = i32;
struct ConcurrentCache {
inner: RwLock<HashMap<CacheKey, CacheValue>>,
}
impl ConcurrentCache {
fn new() -> Self {
ConcurrentCache {
inner: RwLock::new(HashMap::new()),
}
}
fn get(&self, key: &str) -> Option<CacheValue> {
self.inner.read().get(key).cloned()
}
fn set(&self, key: CacheKey, value: CacheValue) {
self.inner.write().insert(key, value);
}
}
fn main() {
let cache = ConcurrentCache::new();
let key = String::from("key1");
let value = 42;
cache.set(key.clone(), value);
println!("Cached value: {:?}", cache.get(&key));
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!