gopl-zh.github.com/vendor/gopl.io/ch5/squares/main.go
github-actions[bot] ca571eb691 deploy: 06a1bdf735
2022-08-04 06:59:33 +00:00

31 lines
561 B
Go

// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 135.
// The squares program demonstrates a function value with state.
package main
import "fmt"
//!+
// squares returns a function that returns
// the next square number each time it is called.
func squares() func() int {
var x int
return func() int {
x++
return x * x
}
}
func main() {
f := squares()
fmt.Println(f()) // "1"
fmt.Println(f()) // "4"
fmt.Println(f()) // "9"
fmt.Println(f()) // "16"
}
//!-