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

INHTWAMA #4280

Closed
jesse99 opened this issue Dec 24, 2012 · 3 comments
Closed

INHTWAMA #4280

jesse99 opened this issue Dec 24, 2012 · 3 comments
Labels
A-lifetimes Area: lifetime related C-enhancement Category: An issue proposing an enhancement or a PR with one.
Milestone

Comments

@jesse99
Copy link
Contributor

jesse99 commented Dec 24, 2012

The current borrow checker can be quite difficult to work around. imagine-never-hearing-the-phrase-aliasable has some ideas for improvements.

@jesse99
Copy link
Contributor Author

jesse99 commented Dec 24, 2012

I ran into an annoying problem with the borrow checker for a very common sort of operation: maintaining a cache with a LinearMap. Here is an example:

extern mod std;
use core::send_map::linear::{LinearMap};

pub type Cache = LinearMap<~str, ~str>;

fn animal_noise(cache: &mut Cache, animal: ~str) -> ~str
{
    fn find_noise(animal: ~str) -> ~str
    {
        let noises = ~[(~"dog", ~"The dog barks."), (~"cat", ~"The cat meows."), (~"cow", ~"The cow moos.")];
        match do noises.position |x| {x.first_ref() == &animal}
        {
            option::Some(index) => copy *noises[index].second_ref(),
            option::None => fmt!("Don't know what %s does.", animal)
        }
    }

    match cache.find_ref(&animal)   // currently can't call this because cache is mutable
    {
            Some(noise) => copy *noise,
            None =>
            {
                let noise = find_noise(copy animal);
                cache.insert(animal, copy noise);
                noise
            }
    }
}

#[test]
fn test_noises()
{
    let mut cache = LinearMap();
    assert animal_noise(&mut cache, ~"dog") == ~"The dog barks.";
    assert animal_noise(&mut cache, ~"dog") == ~"The dog barks.";
    assert animal_noise(&mut cache, ~"cat") == ~"The cat meows.";
}

Best fix I have found is to move the cache in and out of the function and introduce a helper function that works like LinearMap::find_ref but returns a copy instead. Bu INHTWAMA would allow &mut pointers to be temporarily frozen which should allow the above to be written in a much more natural manner.

@sanxiyn
Copy link
Member

sanxiyn commented Mar 27, 2013

@nikomatsakis, this is done?

@nikomatsakis
Copy link
Contributor

It's done enough. #5074 is still pending, but that's a more concrete issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lifetimes Area: lifetime related C-enhancement Category: An issue proposing an enhancement or a PR with one.
Projects
None yet
Development

No branches or pull requests

3 participants