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

[Proposal] bindable expression in if let must be available to borrow in else branch #1330

Closed
KalitaAlexey opened this issue Oct 21, 2015 · 3 comments

Comments

@KalitaAlexey
Copy link

Let's assume code

let mut map = HashMap::new();
for item in &items {
    if let Some(values) = map.get_mut(&item) {
        values.push(0);
    } else {
        // This is error now
        map.insert(item, vec![0]);
    }
}

map is borrowed in if let and being borrowed even if binding failed

@apasel422
Copy link
Contributor

While what you are proposing is potentially useful for other reasons, your specific example can be rewritten to use the entry API (which is additionally more efficient because it only performs one key lookup):

use std::collections::HashMap;

fn main() {
    let items = vec!['a', 'b', 'c', 'a', 'b', 'b'];

    let mut map = HashMap::new();

    for item in &items {
        map.entry(item).or_insert(vec![]).push(0);
    }

    println!("{:?}", map);
}

Prints:

{'c': [0], 'b': [0, 0, 0], 'a': [0, 0]}

@oli-obk
Copy link
Contributor

oli-obk commented Nov 4, 2015

duplicate of #811

@steveklabnik
Copy link
Member

Yes, @oli-obk is correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants