title: How can we store a chain of heterogeneous functions in Rust?
body: <p>I'm working on some code where I'm interested in a lazy-evaluated function chain. In other words, it stores all the operations you want, and only evaluates them all together.</p>
  <p>This is very easy when all the functions in the chain take the same type and return the same type. However, I'm stuck on how to make this work when the chain of functions returns a different type each time. This easy case can be seen in the following code:</p>
  <pre class="lang-rust prettyprint-override"><code>struct FuncChain&lt;T&gt; {
      funcs: Vec&lt;fn(T) -&gt; T&gt;
  }
  
  impl&lt;T&gt; FuncChain&lt;T&gt; {
      fn call(&amp;self, input: T) -&gt; T {
          self.funcs.iter().fold(input, |prev, func| func(prev))
      }
  }
  
  fn main(){
      let fc = FuncChain {
          funcs: vec![
              |x| x + 1,  
              |x| x + 2,
              |x| x * 2,
              |x| x - 2,
          ]
      };
      println!(&quot;{}&quot;, fc.call(1));
  }
  </code></pre>
  <p>(<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=dee1bd80d1d88919b8a5c3b43787bf2d" rel="nofollow noreferrer">Playground</a>)</p>
  <p>So in this case we go <code>i32 -&gt; i32 -&gt; i32 -&gt; i32 -&gt; i32</code>.</p>
  <hr />
  <p>What I want to do is a more general case where we go <code>A -&gt; B -&gt; C -&gt; D -&gt; E</code>, meaning that the <code>funcs</code> vector contains: <code>fn(A) -&gt; B</code>, <code>fn(B) -&gt; C</code>, <code>fn(C) -&gt; D</code>, and <code>fn(D) -&gt; E</code>. But how can this type definition be assigned to a struct? I can't create a vector with heterogeneous types, and even if I could, what would the type signature of the struct be?</p>
  <p>I could make a recursive type definition perhaps, where the <code>FuncChain</code> holds a pointer to the first function object, and also the next object in the chain :</p>
  <pre class="lang-rust prettyprint-override"><code>struct FuncChain&lt;S, T, U&gt; {
      func: fn(S) -&gt; T,
      next: FuncChain&lt;T, U, ?&gt;
  }
  
  impl&lt;S, T, U&gt; FuncChain&lt;S, T, U&gt; {
      fn call(&amp;self, input: T) -&gt; T {
          self.funcs.iter().fold(input, |prev, func| func(prev))
      }
  }
  
  fn main(){
      let fc = FuncChain {
          funcs: vec![
              |x| x.toString(),  
              |x| u8::fromStr(x),
              |x| x.toString(),
              |x| i32::fromStr(x),
          ]
      };
      println!(&quot;{}&quot;, fc.call(1));
  }
  </code></pre>
  <p>However of course this won't work, because I can't know the output type of <code>next</code>.</p>
  <p>How can this be done?</p>