douyi1197 2013-07-07 14:11
浏览 38
已采纳

这是一个封闭的例子吗?

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?

  • 写回答

2条回答 默认 最新

  • dongshungou7699 2013-07-07 14:56
    关注

    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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向