Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mutable and immutable reference issue. #13

Open
iFaceless opened this issue Jun 20, 2020 · 0 comments
Open

Mutable and immutable reference issue. #13

iFaceless opened this issue Jun 20, 2020 · 0 comments
Labels
help wanted Extra attention is needed

Comments

@iFaceless
Copy link
Owner

iFaceless commented Jun 20, 2020

In order to pass borrow checking, every key is cloned and pushed into a new vector, which is a little hacky and inefficient.

pub fn for_each<F>(&mut self, f: F) -> Result<()>
where
    F: Fn(&[u8], &[u8]),
{
    // too stupid, just in order to pass borrow checking. 
    // FIXME: find a better way to implement this feature?
    let mut keys = vec![];
    for key in self.keys() {
        keys.push(key.clone());
    }
    
    for key in keys {
        let r = self.get(&key)?;
        if let Some(value) = r {
            f(&key, &value);
        }
    }
    Ok(())
}

Just wonder is there a better way to implement the above feature? HOW?

Following implementation cannot be compiled, we will get error cannot borrow *self as mutable because it is also borrowed as immutable.

pub fn for_each<F>(&mut self, f: F) -> Result<()>
where
    F: Fn(&[u8], &[u8]),
{
    for key in self.keys() {
        let r = self.get(&key)?;
        if let Some(value) = r {
            f(&key, &value);
        }
    }
    Ok(())
}
@iFaceless iFaceless added the help wanted Extra attention is needed label Jun 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant