Menu
CoddyTech

函数捕获状态

Coddy 面向 Python 开发者的 Go 课程的第 22 课,共 48 课。

Python 需要使用 nonlocal 来重新绑定外层函数中的变量。Go 闭包会直接捕获外部局部变量,并可以修改它。分别调用工厂函数会创建彼此独立的局部状态。

函数是值,可以捕获周围的变量。闭包可以在其外层函数返回后保留可变状态。分别调用工厂函数会创建彼此独立的局部变量;返回一个函数并不会自动复制它引用的所有内容。

Python 示例

def sequence():
    n = 0
    def next_value():
        nonlocal n
        n += 1
        return n
    return next_value
next_value = sequence()
print(next_value(), next_value())

源代码输出:

1 2

Go 示例

package main
import ("fmt")
func Sequence() func() int { n:=0; return func() int { n++; return n } }
func main(){next:=Sequence()
fmt.Println(next(),next())}

Go 输出:

1 2
challenge icon

挑战

简单

实现 MakeAdder(base int) func(int) int。返回的函数会将 base 加到它的参数上,且不会改变 base。Solve 会将它应用于 3。

实现声明的 API;返回结果,不要打印。驱动程序会检查必需的 API,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。

你的代码应写在 adder.go、exercise.go 中。main.go 包含提供的输入/输出代码,不能编辑。保持一个扁平的 package main;不要添加第二个 main。

亲手试试

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
f:=MakeAdder(5); g:=MakeAdder(-2); must(f(1)==6 && f(2)==7 && g(1)==-1,"closure API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Python 开发者的 Go中的所有课

自己练习: Go 在线编译器