Rust has established itself as the go-to language for systems programming, offering memory safety without garbage collection. This guide covers advanced patterns for building high-performance systems.
Zero-Cost Abstractions with Generics
use std::collections::HashMap;
use std::hash::Hash;
struct Cache<K, V> {
store: HashMap<K, V>,
max_size: usize,
}
impl<K: Eq + Hash + Clone, V: Clone> Cache<K, V> {
fn new(max_size: usize) -> Self {
Cache {
store: HashMap::with_capacity(max_size),
max_size,
}
}
fn get(&self, key: &K) -> Option<&V> {
self.store.get(key)
}
fn insert(&mut self, key: K, value: V) -> Option<V> {
if self.store.len() >= self.max_size && !self.store.contains_key(&key) {
if let Some(first_key) = self.store.keys().next().cloned() {
self.store.remove(&first_key);
}
}
self.store.insert(key, value)
}
}
// Async runtime with Tokio
#[tokio::main]
async fn main() {
let mut cache = Cache::new(1000);
cache.insert("key".to_string(), vec![1, 2, 3]);
println!("{:?}", cache.get(&"key".to_string()));
}



