GoLang Closures

This is a simple demo of how to do a closure and pass a function in Go.

Lines 5…8 we create a simple function that will just add one. This will be used as an anonymous function later.

Lines 9…12 we create a second anonymous function to make the demo clear.

Line 20 - this is the type for the closure function.

Lines 24…28 this function will return the function with the closure. saved_value is the closure value that will be bound to the function that is returned.

The demo is in the main.

Example (closureDemo.go):

package main

import "fmt"

// Simple function to add 1 - this function will be used as a variable below
func incNumberByOne(value int) int {
	return value + 1
}

// Add 10 function
func incNumberByTen(value int) int {
	return value + 10
}

// ---------------------------------------------------------------------------------------------
// Setting up a "closure" in Go
// ---------------------------------------------------------------------------------------------

// Create a type for the function
type addToSavedValue func(digit int) int

// Create the "closure" function that will save passed data for later and return a
// function bound to the passed data.
func getFuncUsingSavedValue(saved_value int) addToSavedValue {
	return func(passed_value int) int {
		return passed_value + saved_value
	}
}

func main() {
	// Demo of variable referencing a function.
	simp_func := incNumberByOne // Example of having a variable reference a function
	fmt.Printf("simple function, increment 2 = %d, [[Hint: should be 3]]\n", simp_func(2))
	simp_func = incNumberByTen
	fmt.Printf("simple function, add 10 to 2 = %d, [[Hint: should be 12]]\n", simp_func(2))

	// Demo of a "closure"
	add20func := getFuncUsingSavedValue(20)
	sub100func := getFuncUsingSavedValue(-100)
	fmt.Printf("Saved value is 20, adding 5 to it = %d, [[Hint: should be 20+5 = 25]]\n", add20func(5))
	fmt.Printf("Saved value is -100, adding 1 to it = %d, [[Hint: should be -100+1 = -99]]\n", sub100func(1))
}



•       •       •       •       •       •

Summary: # of Words: 202
Author: Philip J. Schlump
Published On: 2013-11-16

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens