概述

  • 函数式编程
    • 闭包
  • 资源管理出错处理
    • defer调用 确保在函数结束时调用
    • defer 先入后出

Go 基础学习 函数式编程 - 图1

代码

  1. package main
  2. import "fmt"
  3. func adder() func(int) int {
  4. sum := 0
  5. return func(v int) int {
  6. sum += v
  7. return sum
  8. }
  9. }
  10. type iAdder func(int) (int, iAdder)
  11. func adder2(base int) iAdder {
  12. return func(v int) (int, iAdder) {
  13. return base + v, adder2(base + v)
  14. }
  15. }
  16. func main() {
  17. // a := adder() is trivial and also works.
  18. a := adder2(0)
  19. for i := 0; i < 10; i++ {
  20. var s int
  21. s, a = a(i)
  22. fmt.Printf("0 + 1 + ... + %d = %d\n",
  23. i, s)
  24. }
  25. }

函数实现接口

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "golearn/functional/fib"
  8. )
  9. type intGen func() int
  10. func (g intGen) Read(
  11. p []byte) (n int, err error) {
  12. next := g()
  13. if next > 10000 {
  14. return 0, io.EOF
  15. }
  16. s := fmt.Sprintf("%d\n", next)
  17. // TODO: incorrect if p is too small!
  18. return strings.NewReader(s).Read(p)
  19. }
  20. func printFileContents(reader io.Reader) {
  21. scanner := bufio.NewScanner(reader)
  22. for scanner.Scan() {
  23. fmt.Println(scanner.Text())
  24. }
  25. }
  26. func main() {
  27. var f intGen = fib.Fibonacci()
  28. printFileContents(f)
  29. }

image.jpeg