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.
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.
use rand::Rng;
struct Expression_Node<'a> {
val: &'a str,
left: Option<Box<Expression_Node<'a>>>,
right: Option<Box<Expression_Node<'a>>>,
}
fn Create_Expression(
operators: Vec<&str>,
p: i32,
) -> std::option::Option<std::boxed::Box<Expression_Node<'_>>> {
if p == 0 {
let value = String::from(rand::thread_rng().gen::<f64>().to_string());
let value2: &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: &str = *rand::thread_rng().choose(&operators).unwrap();
println!("VAL: {:?}", value);
if value == "ELEM" {
let value = rand::thread_rng().gen::<f64>().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));
}
The error:
error[E0515]: cannot return value referencing local variable `value`
--> src/lib.rs:22:16
|
15 | let value2: &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