1

I defined a recursive function that creates a tree-like structure from another. The value created inside the function can't get out.

I've tried different ways of getting ownership out of the function, returning the value itself, passing a vector as argument to store the value.

#[derive(Clone, Copy)]
pub enum Concept<'a> {
    Variable,
    Base(&'a str),
    ForAll(&'a str, &'a Concept<'a>),
}

pub fn normal_form_reduction<'a>(
    con: &Concept<'a>,
    container: &mut Vec<Concept<'a>>,
) -> Concept<'a> {
    match *con {
        // bases cases without recurrence
        Concept::Variable => Concept::Variable,
        Concept::Base(s) => Concept::Base(&*s),
        //...

        //first recursive call
        Concept::ForAll(s, c) => {
            let nc = normal_form_reduction(c, container);
            (*container).push(nc);
            Concept::ForAll(s, &nc)
        }
    }
}

Expected to compile. Get:

error[E0515]: cannot return value referencing local variable `nc`
  --> src/lib.rs:22:13
   |
22 |             Concept::ForAll(s, &nc)
   |             ^^^^^^^^^^^^^^^^^^^---^
   |             |                  |
   |             |                  `nc` is borrowed here
   |             returns a value referencing data owned by the current function

The error 'E0515' don't explain my error.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • 1
    What the error says is you're trying to store a reference to a local structure, which will disappear as soon as the block is finished. Depending on parts we don't see, a solution might be to store the value itself (in necessary into a Box). – Denys Séguret Apr 05 '19 at 07:49
  • @Stargateur, code edited, should give the wanted error. – horacio tellez Apr 05 '19 at 08:30
  • Hi @horaciotellez! As others already pointed out, the problem is that you are trying to return a reference to a local variable (`nc`). This just won't work and the linked answer explains why. The "solution" depends on your program structure. As Denys pointed out, one possibility might be to store the recursive `Concept` as `Box` instead of `&Concept`. In any case: your `Concept`s have to be stored *somewhere*. If you are unsure how to proceed, I would advise you to ask on the Rust subreddit, the [users forum](https://users.rust-lang.org/) for general advice. Good luck! – Lukas Kalbertodt Apr 05 '19 at 09:50

0 Answers0