rozerro
rozerro

Reputation: 7196

Two function names after func keyword - what is it?

How to understand the last function? Why do we use different function names after func declaration? How to use those function? Using it like shown in the main function is wrong.

package main

import (
    "fmt"
)

func main() {
    fmt.Println(incrementer()) //error
}

func incrementer() func() int { //what is it?!
    i := 0
    return func() int {
        i++
        return i
    }
}

Upvotes: 2

Views: 111

Answers (2)

tmcnicol
tmcnicol

Reputation: 566

It just means that the function is returning a function that takes no parameters and returns an integer. That is what the

... func() int 

part of your signature is saying.

The error you are getting is because you fmt.Println cannot print a function. To show this you can see that you get the same error if you call,

func main() {
    fmt.Println(foo)
}

func foo() int {
  return 1
}

It might be clearer to see what is going on if you call your function like this.

func main() {
    myIncrementer := incrementer()
    fmt.Println(myIncrementer()) // Prints 1
}

Where you are creating incrementer, which is a function, then calling that function function which returns 1.

Upvotes: 6

robert
robert

Reputation: 811

Simply, since incrementer() returns a function, the function that it returns must be called as well. You can do so like this:

functionFoo := incrementer()
fmt.Println(functionFoo())

Or this shorthanded way:

fmt.Println(incrementer()())

Which achieves the same thing, you just immediately execute the function that incrementer() returns.

Upvotes: 5

Related Questions