设计一个函数,每调用一次,函数输出值 +1

 之前曾经看过一道面试题,设计一个函数,每调用一次,函数输出值 +1 ,今天看了Go的闭包,记录一下

顺便推荐一个Go 学习网站,

GO by example

https://gobyexample.com

中文版

https://books.studygolang.com/gobyexample/

程序原文地址  https://books.studygolang.com/gobyexample/closures/

package main

import "fmt"

// 这个 `intSeq` 函数返回另一个在 `intSeq` 函数体内定义的
// 匿名函数。这个返回的函数使用闭包的方式 _隐藏_ 变量 `i`。
func intSeq() func() int {
	i := 0
	return func() int {
		i += 1
		return i
	}
}

func main() {

	// 我们调用 `intSeq` 函数,将返回值(也是一个函数)赋给
	// `nextInt`。这个函数的值包含了自己的值 `i`,这样在每
	// 次调用 `nextInt` 时都会更新 `i` 的值。
	nextInt := intSeq()

	// 通过多次调用 `nextInt` 来看看闭包的效果。
	fmt.Println(nextInt())
	fmt.Println(nextInt())
	fmt.Println(nextInt())

	// 为了确认这个状态对于这个特定的函数是唯一的,我们
	// 重新创建并测试一下。
	newInts := intSeq()
	fmt.Println(newInts())
}

在接口这节课中作者推荐了一篇博客,是汤不热上的(没想到汤上还有技术博客,一直拿它当“小网站”来着 [捂脸] )

http://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go

猜你喜欢

转载自blog.csdn.net/HammerTien/article/details/86535597