0

I want to run a recursive closure inside a rust function implementation for a recursive Struct.

Simplified Example:

Rust Playground Link

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

  • What is the issue? An error? Please include the full error from `cargo check` (a link to the playground will also be good). – Chayim Friedman Jul 03 '22 at 20:01
  • Besides, I feel that in your example there is no need for a closure. It's the job of a regular function, although Rust does not have the tail recursion optimisation so maybe a loop would be better. – jthulhu Jul 03 '22 at 20:04
  • added playground link – tatoci5107 Jul 03 '22 at 20:09
  • how would i do this in a loop? – tatoci5107 Jul 03 '22 at 20:09
  • 1
    Does this answer your question? [Is it possible to make a recursive closure in Rust?](https://stackoverflow.com/questions/16946888/is-it-possible-to-make-a-recursive-closure-in-rust) – Chayim Friedman Jul 03 '22 at 20:26
  • 1
    Does this answer your question? [Is it possible to make a recursive closure in Rust?](https://stackoverflow.com/questions/16946888/is-it-possible-to-make-a-recursive-closure-in-rust) – Jmb Jul 04 '22 at 07:22

0 Answers0