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

Rust could release borrows in match against the matched object in some cases #35132

Closed
toumorokoshi opened this issue Jul 30, 2016 · 2 comments
Closed

Comments

@toumorokoshi
Copy link

It seems like Rust's borrow checker could be more lenient on match checks where the match is an enum with no references to the object being matched.

I tried this code:

use std::collections::HashMap;

fn main() {
    let mut my_map: HashMap<String, String> = HashMap::new();
    lazy_get(&mut my_map, String::from("foo"));
}

/*
// what I want to do, but it leads to an error
fn lazy_get(map: &mut HashMap<String, String>, key: String) -> String {
    match map.get(&key) {
        Some(v) => v.clone(),
        None => {
            let new_val = key.clone();
            map.insert(new_val, new_val);
            new_val
        }
    }
} */

// my workaround
fn lazy_get(map: &mut HashMap<String, String>, key: String) -> String {
    if let None = map.get(&key) {
        let new_value = key.clone();
        map.insert(key.clone(), new_value.clone());
        return new_value;
    }
    match map.get(&key) {
        Some(v) => v.clone(),
        // this case will never happen, but I have to add it
        // to satisfy all matches.
        None => key.clone()
    }
}

I expected to see this happen:

In the commented example, I would expect that if the map is matched to None, it would release the borrow on the map, thereby allowing me to mutate it. For this particular case, it would make the code a bit cleaner, by omitting unused code that exists for the sake of the match completeness.

Instead, this happened: borrow checker complains about an immutable borrow existing previously.

Tried this on the rust playground, against the nightly as well.

@Stebalien
Copy link
Contributor

@steveklabnik
Copy link
Member

Yes, this will be fixed by non-lexical lifetimes. Thanks for filing! We agree, but we're already tracking it 😄

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

3 participants