rust crud example with vector
Here is an example of how you might implement CRUD (create, read, update, delete) operations in Rust using a Vec
:
rust crud example with vector
struct DataStore { store: Vec<(String, String)>, } impl DataStore { fn new() -> DataStore { DataStore { store: Vec::new() } } fn create(&mut self, key: String, value: String) { self.store.push((key, value)); } fn read(&self, key: &str) -> Option<&String> { for (k, v) in &self.store { if k == key { return Some(v); } } None } fn update(&mut self, key: &str, value: String) { for (k, v) in &mut self.store { if k == key { *v = value; } } } fn delete(&mut self, key: &str) { self.store.retain(|(k, _)| k != 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("key", String::from("new value")); // Delete an entry data_store.delete("key"); }
This example defines a DataStore
struct that contains a Vec
field to store the key-value pairs. The create
, read
, update
, and delete
methods provide the necessary functionality for implementing CRUD operations.
Note that the read
method returns an Option<&String>
, which allows you to handle the case where the key is not found in the store. The update
and delete
methods take &str
arguments instead of String
s to avoid moving the key value out of the store.