rust crud example with hashmap
here is a simplified example of how you might implement CRUD (create, read, update, delete) operations in Rust:
rust crud example with hashmap
use std::collections::HashMap; struct DataStore { store: HashMap<String, String>, } impl DataStore { fn new() -> DataStore { DataStore { store: HashMap::new() } } fn create(&mut self, key: String, value: String) { self.store.insert(key, value); } fn read(&self, key: &str) -> Option<&String> { self.store.get(key) } fn update(&mut self, key: String, value: String) { self.store.insert(key, value); } fn delete(&mut self, key: &str) { self.store.remove(key); } } fn main() { let mut data_store = DataStore::new(); // Create a new entry data_store.create(String::from("key"), String::from("value")); // Read an entry let value = data_store.read("key"); println!("{:?}", value); // Update an entry data_store.update(String::from("key"), String::from("new value")); // Delete an entry data_store.delete("key"); }
This example uses a HashMap
to store the key-value pairs in the DataStore
struct. The create
, read
, update
, and delete
methods provide the necessary functionality for implementing CRUD operations.