I want to run a recursive closure inside a rust function implementation for a recursive Struct.
Simplified Example:
enum Enum {
T1,
T2,
T3
}
// StructExample is a Recursive struct.
struct StructExample {
value_type: Enum,
value: Option<Box<StructExample>>
}
impl StructExample {
fn to_str(&self) -> String {
let mut string_var = String::new();
let mut first = true;
let mut recursive = |s: &Self| {
match s.value_type {
Enum::T1 => {
// Not the exact logic...but i need to check if its the
// first iteration and do some complex logic
if first {
string_var.push('i');
first = false;
}
string_var.push('H');
}
Enum::T2 => {
// Not the exact logic...but i need to check if its the
// first iteration and do some complex logic
if first {
string_var.push('H');
first = false;
}
string_var.push('i');
}
Enum::T3 => {
if let Some(val) = s.value {
first = false;
string_var.push('<');
// I dont want to use val.to_str()
// really need recursive call
recursive(&val); // <<< cannot find function `recursive` in
// this scope not found in this scope
// rustc (E0425)
string_var.push('>');
}
}
}
};
recursive(self);
string_var
}
}
How can I fix this issue. I really need this kind of recursion. Im converting a struct to html like string. Coming from JS, IDK if I'm trying to javascript-ify my rust.
Edit 1: Added some comments to clear the context Edit 2: Added playground link