jonas-schulze
jonas-schulze

Reputation: 268

How to instantiate function types in golang?

I would like to instantiate a bunch of functions of the same type without having to duplicate their signature. I already have a function type describing that signature (fancyFunc below) and another function consuming arguments of that kind (doFancyStuff below). How would I make something like this work?

package main

import "fmt"

type fancyFunc func(a,b,c int) int

func doFancyStuff(f FancyFunc) int {
    // Do something special with f
    return 42
}

func main() {
    // This works but is rather tedious:
    f1 := func(a,b,c int) int { return a + b + c }

    // I would like to create them like this:
    f2 := fancyFunc{ return a * b * c }

    // Eventually, they are used like this:
    fmt.Println(doFancyStuff(f1))
    fmt.Println(doFancyStuff(f2))
}

Upvotes: 1

Views: 1156

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49285

You can only do it as in the f1 case, or by defining a normal function. there is nothing like the f2 way. In C people do this with macros, but Go doesn't have a preprocessor (there are a few unofficial ones you can use).

Upvotes: 8

Related Questions