First class functions in Go

Today, I played with functions as objects in the Go programming language. If functions are first class citizens in Go then it must be possible to store them in fields of a struct, pass them as arguments to other functions and use them as return values of other functions.

So I visited play.golang.org for putting together a simple program that demonstrates this.

package main

import "fmt"

func CallWith(f func(string), who string) {
    f(who)
}

type FunctionHolder struct {
    Function func(string)
}

func main() {
    holder := FunctionHolder{ func(who string) { fmt.Println("Hello,", who) }}
    CallWith(holder.Function,"ernest")
}

  • The CallWith function takes a one string parameter function f and a string parameter who. The body of the CallWith function evaluates the function parameter with the string parameter.
  • The FunctionHolder is a struct type with a field called Function which must be a function with a string parameter.
  • In the main function, a FunctionHolder is created initializing the Function field with a function that prints an Hello message.
  • Next in the main function, the CallWith function is called with the Function value of the holder and a string value.
On play.golang.org can run this program yourself

comments powered by Disqus