0

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?

  • I don't understand the question. Are you asking why there is a deref here even though you didn't explicitly write `*`? – Chayim Friedman Aug 09 '22 at 07:49
  • Auto-dereferencing is a thing. Please edit the question if the linked questions do not clarify your concern. – E_net4 Aug 09 '22 at 08:11

0 Answers0