Menu
CoddyTech

Functions capture state

Lesson 22 of 48 in Coddy's Go for C# Developers course.

C# lambdas can capture mutable locals and are represented through delegate types. Go func values also capture surrounding variables and can outlive the creating call. Go does not require a named delegate declaration.

Functions are values and may close over surrounding variables. A closure can retain mutable state after its enclosing function returns. Separate factory calls have separate local variables; returning a function does not automatically duplicate everything that it references.

C# example

using System;
using System.Collections.Generic;
using System.Linq;
static class Helpers{public static Func<int> Sequence(){int n=0;return ()=>++n;}}
class Program { static void Main() {
Func<int> next=Helpers.Sequence();Console.WriteLine(next()+" "+next());
} }

Source output:

1 2

Go example

package main
import ("fmt")
func Sequence() func() int { n:=0; return func() int { n++; return n } }
func main(){next:=Sequence()
fmt.Println(next(),next())}

Go output:

1 2
challenge icon

Challenge

Easy

Implement MakeAdder(base int) func(int) int. Returned function adds base to its argument without changing base. Solve applies it to 3.

Implement the declared APIs; return results without printing. The driver checks required APIs and preserves caller input. Collection stdout uses Go bracket formatting, not JSON.

Your code goes in adder.go, exercise.go. main.go holds the supplied input/output code and cannot be edited. Keep one flat package main; do not add a second main.

Try it yourself

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
f:=MakeAdder(5); g:=MakeAdder(-2); must(f(1)==6 && f(2)==7 && g(1)==-1,"closure API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Go for C# Developers

Practice on your own: Online Go compiler