A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wuqiong 金牌黑马   /  2018-7-20 10:00  /  1291 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

概述
  • 函数式编程

    • 闭包


  • 资源管理出错处理

    • defer调用 确保在函数结束时调用

    • defer 先入后出



代码package main

import "fmt"

func adder() func(int) int {
        sum := 0
        return func(v int) int {
                sum += v
                return sum
        }
}

type iAdder func(int) (int, iAdder)

func adder2(base int) iAdder {
        return func(v int) (int, iAdder) {
                return base + v, adder2(base + v)
        }
}

func main() {
        // a := adder() is trivial and also works.
        a := adder2(0)
        for i := 0; i < 10; i++ {
                var s int
                s, a = a(i)
                fmt.Printf("0 + 1 + ... + %d = %d\n",
                        i, s)
        }
}

函数实现接口
package main

import (
        "bufio"
        "fmt"
        "io"
        "strings"

        "golearn/functional/fib"
)

type intGen func() int

func (g intGen) Read(
        p []byte) (n int, err error) {
        next := g()
        if next > 10000 {
                return 0, io.EOF
        }
        s := fmt.Sprintf("%d\n", next)

        // TODO: incorrect if p is too small!
        return strings.NewReader(s).Read(p)
}

func printFileContents(reader io.Reader) {
        scanner := bufio.NewScanner(reader)

        for scanner.Scan() {
                fmt.Println(scanner.Text())
        }
}

func main() {
        var f intGen = fib.Fibonacci()
        printFileContents(f)
}



6 个回复

倒序浏览
优秀,奈斯
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
回复 使用道具 举报
奈斯,很赞
回复 使用道具 举报
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马