mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2024-11-16 19:33:47 +00:00
31 lines
561 B
Go
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"
|
|
}
|
|
|
|
//!-
|