Search code examples
functionrustreturnreturn-type

How do I write a function that returns itself?


What I want to make is a function, that returns itself, so I can call it like this:

foo()()...()

In C# it would be done via delegates:

delegate SelfFunc SelfFunc();

static void Main() {
    SelfFunc foo = null;
    foo = () => {
        return foo;
    };
    foo()()...();
}

Anticipating questions like "why implement such silly behavior?": I want to sum numbers in a very strange way using single function continues calls: foo(1)(2)(3)() = 6, but in this question I just want to know how to return function itself. Example realization of this method that I made in C#. This is all just for fun and to learn Rust:

static int sum = 0;
delegate dynamic InfFunc(int i = int.MaxValue);
 
static void InfFuncTest() {
    InfFunc f = null;
    f = (int i) => {
        if(i == int.MaxValue) {
            return sum;
        }
        sum += i;
        return f;
    };
 
    var g = f;
    var value = g(1)(2)(3)();
    Console.WriteLine(value);
}

Solution

  • A function that returns itself is possible on nightly.

    First you need to enable the features unboxed_closures and fn_traits.

    Then you can define a struct which, when called, returns self. The full code looks something like this:

    #![feature(unboxed_closures, fn_traits)]
    
    struct SelfFunc;
    
    impl FnOnce<()>  for SelfFunc {
        type Output = SelfFunc;
    
        extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
            self
        }
    }
    

    Then you can call the function as many times as you want:

    fn main() {
      let f = SelfFunc;
      f()()()()()();
    }