Skip to content

Possibly invalid borrowing actually allowed #4856

@alexcrichton

Description

@alexcrichton

For something like this program:

use core::hashmap::linear::LinearSet;

struct Foo {
  n: LinearSet<int>,
}

impl Foo {
  fn foo(&mut self, fun: fn(&int)) {
    for self.n.each |f| {
      fun(f);
    }
  }
}

fn bar(f: &mut Foo) {
  do f.foo |a| {
    f.n.insert(*a);
  }
}

fn main() {
  let mut f = Foo { n: LinearSet::new() };
  bar(&mut f);
}

The program both compiles and runs just fine. I thought that this should be an error, though. In the Foo::foo method, the field n is cast to an immutable borrowed pointer for the duration of the iteration, and it then yields a pointer to inside itself to fun. There are no restrictions on fun, however, so if fun does something like insert into n, it might invalidate the pointer due to something like resizing.

Should this actually be allowed or disallowed? I was hoping it would be disallowed because it seems like a bug to me. I also don't want to see pure come back though...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions