Skip to content

The lifetime of the borrowed value is too long #9113

Closed
@zeux

Description

@zeux

I'm not sure of the correct bug title here, it's based on my limited understanding of the problem :)

I'm trying to write a DB wrapper with a cache. Here's a code sample with two variants of read() function, the DB is using a hash map as well for exposition.

use std::hashmap::HashMap;

#[deriving(Clone)]
struct Data {
    data: ~[u8]
}

struct DB {
    cache: HashMap<int, Data>,
    db: HashMap<int, Data>
}

impl DB {
    pub fn read1<'a>(&'a mut self, key: int) -> Option<&'a Data> {
        match self.cache.find(&key) {
            Some(data) => return Some(data),
            None => ()
        };

        match self.db.find(&key) {
            Some(data) => {
                let result: &Data = self.cache.find_or_insert(key, data.clone());

                Some(result)
            },
            None => None
        }
    }

    pub fn read2<'a>(&'a mut self, key: int) -> Option<&'a Data> {
        match self.cache.find(&key) {
            Some(data) => return Some(data),
            None => {
                match self.db.find(&key) {
                    Some(data) => {
                        let result: &Data = self.cache.find_or_insert(key, data.clone());

                        Some(result)
                    },
                    None => None
                }
            }
        }
    }
}

fn main() {
}

Both read1() and read2() fail to compile with the following error:

db.rs:22:36: 22:46 error: cannot borrow `(*self).cache` as mutable because it is also borrowed as immutable
db.rs:22                 let result: &Data = self.cache.find_or_insert(key, data.clone());
                                             ^~~~~~~~~~
db.rs:15:14: 15:24 note: second borrow of `(*self).cache` occurs here
db.rs:15         match self.cache.find(&key) {
                       ^~~~~~~~~~

Possibly a duplicate of #6393 (although read1 looked like it could solve the problem but did not).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions