Zeynel
Zeynel

Reputation: 13515

Is this a closure example?

I am reading Closure example in Mark Summerfield's book Programming in Go Section 5.6.3. He defines Closure as a "function which "captures" any constants and variables that are present in the same scope where it is created, if it refers to them."

He says that one use of closure is anonymous functions (or function literals in Go)

He gives this examples:

addPng := func(name string) string { return name + ".png" }
addJpg := func(name string) string { return name + ".jpg" }
fmt.Println(addPng("filename"), addJpg("filename"))

I understand that anonymous function named addPng is a wrapper for the string concatenation operator +.

If I understand correctly, he is assigning an anonymous function a name then calling the function with that name. I don't see the point of this example. If I define the same function addPng and call it inside main() I get the same result:

package main

import ("fmt")

func addPng (name string) string {
    return name + ".png"
    }

func main() {
    fmt.Println(addPng("filename"))
}

I understand that I cannot define and use a function inside another function. But why is the anonymous function in Summerfield's example called "Closure"? And why use a wrapper function? What am I missing?

Upvotes: 1

Views: 147

Answers (2)

peterSO
peterSO

Reputation: 166569

Here's an example of using a closure for state representation.

package main

import "fmt"

func NextFibonacci() func() int {
    a, b := 0, 1
    return func() (f int) {
        f, a, b = a, b, a+b
        return
    }
}

func main() {
    nf := NextFibonacci()
    f := make([]int, 7)
    for i := range f {
        f[i] = nf()
    }
    fmt.Println(len(f), f)
}

Output:

7 [0 1 1 2 3 5 8]

Upvotes: 3

zzzz
zzzz

Reputation: 91203

It's not for the first time I see someone referring to this particular book where the cited material is either plain wrong or basically missing the point completely.

Let me stop talking about the book here by suggesting to not use it at all.

For a good and correct definition of a closure, see Wikipedia. Pay attention to the adjective 'lexical'.

Upvotes: 2

Related Questions