Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Currently, borrows are always lexical. It'd be nice to have non-lexical borrows. It's on the todo list.



Interesting. What is an example of a non-lexical borrow that could potentially be proven safe?


Searching[1] a data-structure (like a hashmap) will return a borrowed reference to that data, which "freezes" the hashmap while the borrow exists. And, due to lexical borrowing, it is frozen even if there was nothing (that is, if the return value was `None` which contains no references linked to the original map).

The following is currently illegal because the `insert` is trying to modify the borrowed map.

  match some_map.find(&a_key) {
      Some(x) => println!("reference to value {}", x),
      None => {
          println!("not found, inserting instead");
          some_map.insert(a_key, some_value);
      }
  }
#6393 is the relevant issue.

[1]: http://doc.rust-lang.org/nightly/std/collections/struct.Hash... [6393]: https://github.com/rust-lang/rust/issues/6393


How exactly does one decide if scope is lexical or non-lexical? Or more precisely how do you tell compiler?


There is a Drop trait that has one method, drop(). It's like a destructor. It's called for you, but you can also call it yourself.

    fn foo(x: &something) {
        // stuff
        x.drop();
        // more stuff,
    } // if we didn't drop, x gets drop()-ped here
If we had non-lexical borrows, after we drop x, we could have it be un-borrowed. currently, x is still considered borrowed until the end of foo(). This is sort of a contrived example, but if you check out the ticket it has better ones.

There's also good examples here: http://www.reddit.com/r/rust/comments/2hy06n/a_fresh_look_at...




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: