mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 22:52:05 +00:00
good good study, day day up!
This commit is contained in:
30
vendor/gopl.io/ch5/squares/main.go
generated
vendored
Normal file
30
vendor/gopl.io/ch5/squares/main.go
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
// 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"
|
||||
}
|
||||
|
||||
//!-
|
Reference in New Issue
Block a user