I am looking for advice here. Could someone please tell me if this is right way to structure code in Rust? In particular please look at the open() method which uses locks. The code works but I am looking for validation as to whether this is the right way to code when employing locks.
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::collections::HashMap;
struct Table<'a>
{
name_ : &'a str
}
impl<'a> Table<'a>
{
fn new(name : &'a str) -> Self
{
return Self {
name_ : name
}
}
fn name(&self) -> &str
{
return self.name_;
}
}
struct TableManager<'a>
{
tables_ : RwLock<HashMap<&'a str, Arc<Table<'a>>>>
}
impl<'a> TableManager<'a>
{
fn new() -> Self
{
return Self {
tables_ : RwLock::new(HashMap::new()),
}
}
**fn open(&mut self, name : &'a str) -> Arc<Table>**
{
{
let rd_guard = self.tables_.read().unwrap();
let table = rd_guard.get(name);
if let Some(table) = table
{
return Arc::clone(&table);
}
}
{
let mut wr_guard = self.tables_.write().unwrap();
let table = wr_guard.get(name);
if table.is_none()
{
let table = Table::new(name);
wr_guard.insert(name, Arc::new(table));
}
}
let rd_guard = self.tables_.read().unwrap();
let table = rd_guard.get(name);
return Arc::clone(&table.unwrap());
}
}
fn main() -> ()
{
let mut table_mgr = TableManager::new();
let table = table_mgr.create_table("System");
println!("{}", table.name());
}