A new product!

Social Media Toolkit

Download our all in one automation tool for various social media websites.

Gopher

Function closures in Golang

Published on 29 March 2020
Last Updated on 29 March 2020

A Function is called closure if it references variables from outside of its function body.

A function may access and assign to the referenced variable. A closure is bound the variable that is being referenced.

Program given below demonstrates a closure that references a variable named sliceOfWords that is outside its function body.

// function being treated as return value
package main

import (
	"fmt"
	"strings"
)

// function that returns a closure
func wordList() func(string) string {
	// closure will access this variable
	var sliceOfWords []string

	// return closure
	return func(word string) string {
		sliceOfWords = append(sliceOfWords, word)
		return strings.Join(sliceOfWords, " ")
	}
}

func main() {
	// assign a new closure
	closure:=wordList()

	// pass new words to the closure and print the return value
	fmt.Println(closure("apple"))
	fmt.Println(closure("banana"))
	fmt.Println(closure("cat"))
	fmt.Println(closure("dog"))
}

Program output

Above program produces following output:

apple
apple banana
apple banana cat
apple banana cat dog

Program Description

Whenever closure is called, new word that is passed to the closure is added to its existing sliceOfWords. Closure joins all elements present in the sliceOfWords and returns it as a string, this string is then printed to the console using the fmt.Println function.