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条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题