gopl-zh.github.com/vendor/gopl.io/ch5/squares/main.go
2015-12-09 15:45:11 +08: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"
}
//!-