dragon7088 2017-08-16 18:08
浏览 56

去重置闭包变量

I came upon an example of closures in Go here: https://gobyexample.com/closures

It gives a pretty straight-forward example of closure scoping in Go. I changed how i is initialized from "i := 0" to "i := *new(int)".

func intSeq() func() int {
    i := *new(int)
    return func() int {
        i += 1
        return i
    }
}

func main() {

    // We call `intSeq`, assigning the result (a function)
    // to `nextInt`. This function value captures its
    // own `i` value, which will be updated each time
    // we call `nextInt`.
    nextInt := intSeq()

    // See the effect of the closure by calling `nextInt`
    // a few times.
    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    // To confirm that the state is unique to that
    // particular function, create and test a new one.
    newInts := intSeq()
    fmt.Println(newInts())
}

The output of this is still 1, 2, 3, 1. Does the variable 'i' in intSeq() not get reallocated everytime nextInt() in main() is called?

  • 写回答

3条回答 默认 最新

  • dongti8535 2017-08-16 18:19
    关注

    There is no point in doing i := *new(int). That line says:

    1. Allocate a new int
    2. Create a pointer to it
    3. Dereference the pointer
    4. Assign the value to i

    This is no different from i := 0 or var int i, but there's the extra step in the middle of creating, dereferencing, and discarding the pointer that never gets used.

    If you want a pointer to an int, use i := new(int). *new anywhere is a pointless invocation and a code smell.

    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法