title: How to solve "returns a value referencing data owned by the current function" error in Rust?
body: <p>I'm trying to code a binary tree that generates random expressions. I need random numbers and a set of functions. I receive a vector with the functions and the depth for the expression in the tree. In the operators vector, I also include a "ELEM" string, this is used to choose a random element from the vector and then change it for a float.</p>
  
  <p>It seems I still do not understand the exact use for borrows, moving and ownership, since it is a recursive function, it shows the error saying that value has been borrowed and cannot return a local variable.</p>
  
  <pre><code>use rand::Rng;
  
  struct Expression_Node&lt;'a&gt; {
      val: &amp;'a str,
      left: Option&lt;Box&lt;Expression_Node&lt;'a&gt;&gt;&gt;,
      right: Option&lt;Box&lt;Expression_Node&lt;'a&gt;&gt;&gt;,
  }
  
  fn Create_Expression(
      operators: Vec&lt;&amp;str&gt;,
      p: i32,
  ) -&gt; std::option::Option&lt;std::boxed::Box&lt;Expression_Node&lt;'_&gt;&gt;&gt; {
      if p == 0 {
          let value = String::from(rand::thread_rng().gen::&lt;f64&gt;().to_string());
          let value2: &amp;str = value.as_ref();
          //println!("{:?}", value);
          let new_node = Expression_Node {
              val: value2,
              left: None,
              right: None,
          };
          return Some(Box::new(new_node));
      }
      let value: &amp;str = *rand::thread_rng().choose(&amp;operators).unwrap();
      println!("VAL: {:?}", value);
      if value == "ELEM" {
          let value = rand::thread_rng().gen::&lt;f64&gt;().to_string();
      }
  
      let new_node = Expression_Node {
          val: value,
          left: Create_Expression(operators.clone(), p - 1),
          right: Create_Expression(operators.clone(), p - 1),
      };
      return Some(Box::new(new_node));
  }
  </code></pre>
  
  <p>The error:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0515]: cannot return value referencing local variable `value`
    --&gt; src/lib.rs:22:16
     |
  15 |         let value2: &amp;str = value.as_ref();
     |                            ----- `value` is borrowed here
  ...
  22 |         return Some(Box::new(new_node));
     |                ^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
  </code></pre>