3
type ApplyFunc func(commitIndex uint64, cmd []byte) []byte

For this declaration. My understanding is,this is a function pointer. Its name is ApplyFunc. And this function takes commitIndex and cmd as inputs. It returns []byte.

Is my understanding right? thanks!

BufBills
  • 8,005
  • 12
  • 48
  • 90
  • 5
    Almost, just two misconceptions: First `ApplyFunc` is a type (a named type) and not a function or a pointer to a function. Variables of type ApplyFunc will be functions. Second: It is not a "pointer" (not even a pointer type). To get a pointer you need something to point to, e.g. by `var af ApplyFunc = func(uint64,[]byte) []byte {return nil}` and then taking the address `afp := &af` – Volker Aug 26 '14 at 08:37

1 Answers1

7

Golang function are first-class, as illustrated in this go-example page.

It is a named type, which means you can use ApplyFunc anywhere where a func(commitIndex uint64, cmd []byte) []byte is expected: see "Golang: Why can I type alias functions and use them without casting?".

It means, as commented by Volker, it isn't a function or a "pointer to a function".
It is a type which allows you to declare a variable storing any function which respects the same func signature as its declared type, like a function literal (or "anonymous function").

var af ApplyFunc = func(uint64,[]byte) []byte {return nil}
                 // (function literal or "anonymous function")

See "Anonymous Functions and Closures": you can define a function which returns another function, taking advantage of closure:

Function literals are closures: they may refer to variables defined in a surrounding function.
Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

(see playground example)

type inc func(digit int) int

func getIncbynFunction(n int) inc {
    return func(value int) int {
        return value + n
    }
}

func main() {
    g := getIncbynFunction
    h := g(4)
    i := g(6)
    fmt.Println(h(5)) // return 5+4, since n has been set to 4
    fmt.Println(i(1)) // return 1+6, since n has been set to 6
}

Also, As illustrated in "Golang function pointer as a part of a struct", you can define functions on a func receiver ApplyFunc(!).

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250