In module db.rs, I have struct Db containing entries field of type <Arc<Mutex<HashMap<String, Bytes>>>. In the implementation of Db(impl Db), i have a function write, which insert or get values from database.
#[derive(Clone, Debug)]
pub struct Db {
pub entries: Arc<Mutex<HashMap<String, Bytes>>>,
}
implementation of Db in db.rs
impl Db {
pub fn new() -> Db {
Db {
entries: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn write(self, arr: &[String]) -> Result<&str, &'static str> {
let key = &arr[1];
let value = &arr[2];
let val = value.clone();
let p = self
.entries
.lock()
.unwrap()
// .get(key); //Coerced to: & Hashmap<String, Bytes>
.insert(String::from(key), Bytes::from(val)); //Coerced to: &mut Hashmap<String, Bytes>
match p {
Some(p) => {
Ok("r Ok")
}, // if they key was already present
None => Ok("Ok"), // if the key was not present
}
}
Here in Write function when i want to get or set data to DataBase, .lock() return the Result<MutexGuard<HashMap<_, _>>> but after .unwrap(), MutexGuard internally is Coerced to to &HashMap and &mut HashMap for.get() and .insert() methods respectively. Since, mutex implements deref and derefmut, these coercion are happening as a result of dereferencing of the smart pointers. but, How is this dereferencing getting triggered under the hood is what I am unclear about. Can anyone dive dipper into the inner functioning of deref in the code?