a function returning a function of type int

78 views
Skip to first unread message

Rino Mardo

unread,
Aug 24, 2022, 1:23:22 AM8/24/22
to golang-nuts
i'm still trying to learn golang when i chance upon the code below. i'm aware of function return types like int or float, and such but not a function. how does one interpret the return value of below code?

package main
import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci(x int) func() int {
  if x <= 1 {
    return x
  } else {
    return fibonacci(x-1) + fibonacci(x-2)
  }
  return 0
}

func main() {
  f := fibonacci()
  for i := 0; i < 10; i++ {
    fmt.Println(f())
  }
}


when run, it shows below errors:

./prog.go:9:10: cannot use x (variable of type int) as type func() int in return statement
./prog.go:11:10: invalid operation: operator + not defined on fibonacci(x - 1) (value of type func() int)
./prog.go:13:9: cannot use 0 (untyped int constant) as func() int value in return statement
./prog.go:17:7: not enough arguments in call to fibonacci
    have ()
    want (int)

Jan Mercl

unread,
Aug 24, 2022, 2:22:04 AM8/24/22
to Rino Mardo, golang-nuts
On Wed, Aug 24, 2022 at 7:23 AM Rino Mardo <rino...@gmail.com> wrote:

Example of a function returning a function: https://go.dev/play/p/9FY0GDhKJNd
Reply all
Reply to author
Forward
0 new messages