Skip to content

"Cannot root managed value long enough" with recursion and returning borrowed pointers #4325

Closed
@ttaubert

Description

@ttaubert

I wonder if this shouldn't work?

struct Node<T> {
  val: T,
  next: Option<@Node<T>>
}

impl<T> Node<T> {
  pure fn get(&self) -> &self/T {
    match self.next {
      Some(next) => next.get(),
      None => &self.val
    }
  }
}

fn main() {}

The failure is:

19:20: 19:24 error: illegal borrow: cannot root managed value long enough
19       Some(next) => next.get(),
                       ^~~~
17:32: 22:3 note: managed value would have to be rooted for the lifetime &self as defined on the block at 17:32...
17   pure fn get(&self) -> &self/T {
18     match self.next {
19       Some(next) => next.get(),
20       None => &self.val
21     }
22   }
17:32: 22:3 note: ...but can only be rooted for the block at 17:32
17   pure fn get(&self) -> &self/T {
18     match self.next {
19       Some(next) => next.get(),
20       None => &self.val
21     }
22   }

https://github.com/mozilla/rust/blob/incoming/src/librustc/middle/borrowck/preserve.rs#L333

attempt_root() expects a ty::re_scope but self.scope_region is a ty::re_free. self.scope_region's id is the same as self.root_ub (root_region's id).

CC'ing @nikomatsakis because he's the borrowed pointer specialist.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions