Creating Closures with Anonymous Functions in Go | Challenge

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you will learn how to use anonymous functions to create closures in Golang.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go/FunctionsandControlFlowGroup -.-> go/closures("`Closures`") subgraph Lab Skills go/closures -.-> lab-15381{{"`Creating Closures with Anonymous Functions in Go | Challenge`"}} end

Closures

You need to create a function that returns another function. The returned function should increment a variable by one each time it is called. The variable should be unique to each returned function.

Requirements

  • The function intSeq should return another function.
  • The returned function should increment a variable by one each time it is called.
  • The variable should be unique to each returned function.

Example

$ go run closures.go
1
2
3
1

## The last feature of functions we'll look at for now is
## recursion.

Summary

In this challenge, you learned how to use anonymous functions to create closures in Golang. Closures are useful when you want to define a function inline without having to name it.

Other Go Tutorials you may like