Skip to content

Instantly share code, notes, and snippets.

@fotcorn
Last active May 9, 2017 15:12
Show Gist options
  • Save fotcorn/6ad36699dfd3dc4919ebeb3ce90f91cb to your computer and use it in GitHub Desktop.
Save fotcorn/6ad36699dfd3dc4919ebeb3ce90f91cb to your computer and use it in GitHub Desktop.

Revisions

  1. fotcorn revised this gist May 9, 2017. 1 changed file with 10 additions and 34 deletions.
    44 changes: 10 additions & 34 deletions test.rs
    Original file line number Diff line number Diff line change
    @@ -34,38 +34,14 @@ fn main() {
    }

    /*
    use std::collections::hash_map::HashMap;
    struct MyStruct {
    a: u64,
    b: u64,
    }
    struct Test {
    counter: u64,
    map: HashMap<u64, MyStruct>,
    }
    impl Test {
    pub fn new() -> Test {
    Test {
    counter: 0,
    map: HashMap::new(),
    }
    }
    pub fn add_if_not_yet_exists(&mut self, key: u64, a: u64, b: u64) {
    self.map.entry(key).or_insert(self.add(a, b));
    }
    pub fn add(&mut self, a: u64, b: u64) -> MyStruct {
    self.counter += 1;
    MyStruct {a: a, b: b}
    }
    }
    fn main() {
    let mut test = Test::new();
    test.add_if_not_yet_exists(1, 2, 3);
    }
    error[E0499]: cannot borrow `*self` as mutable more than once at a time
    --> src/bin/test.rs:22:39
    |
    22 | self.map.entry(key).or_insert(self.add(a, b));
    | -------- ^^^^ - first borrow ends here
    | | |
    | | second mutable borrow occurs here
    | first mutable borrow occurs here
    error: aborting due to previous error
    */
  2. fotcorn created this gist May 9, 2017.
    71 changes: 71 additions & 0 deletions test.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    use std::collections::hash_map::HashMap;

    struct MyStruct {
    a: u64,
    b: u64,
    }

    struct Test {
    counter: u64,
    map: HashMap<u64, MyStruct>,
    }

    impl Test {
    pub fn new() -> Test {
    Test {
    counter: 0,
    map: HashMap::new(),
    }
    }

    pub fn add_if_not_yet_exists(&mut self, key: u64, a: u64, b: u64) {
    self.map.entry(key).or_insert(self.add(a, b));
    }

    pub fn add(&mut self, a: u64, b: u64) -> MyStruct {
    self.counter += 1;
    MyStruct {a: a, b: b}
    }
    }

    fn main() {
    let mut test = Test::new();
    test.add_if_not_yet_exists(1, 2, 3);
    }

    /*
    use std::collections::hash_map::HashMap;
    struct MyStruct {
    a: u64,
    b: u64,
    }
    struct Test {
    counter: u64,
    map: HashMap<u64, MyStruct>,
    }
    impl Test {
    pub fn new() -> Test {
    Test {
    counter: 0,
    map: HashMap::new(),
    }
    }
    pub fn add_if_not_yet_exists(&mut self, key: u64, a: u64, b: u64) {
    self.map.entry(key).or_insert(self.add(a, b));
    }
    pub fn add(&mut self, a: u64, b: u64) -> MyStruct {
    self.counter += 1;
    MyStruct {a: a, b: b}
    }
    }
    fn main() {
    let mut test = Test::new();
    test.add_if_not_yet_exists(1, 2, 3);
    }
    */