• Go 语言为Fibonacci函数实现Read方法


    Go语言非常灵活,只要为对象实现了相应的方法就可以把他看成实现了某个接口,类似于Durk Type,

    为Fibonacci实现Read方法,就可以像读取文件一样,去读取下一个Fibonacci值。

    示例代码:

    ackage main
    
    import (
        "fmt"
        "io"
        "bufio"
        "strings"
        "strconv"
    )
    
    func fibonacci() intGen {
        // 斐波那契数列,返回一个intGen类型
        a, b := 0, 1
        return func() int {
            a, b = b, a + b
            return a
        }
    }
    
    type intGen func() int    // 定义一个func类型,返回int类型
    
    func (g intGen) Read(p []byte) (n int, err error) {
        // 为intGen实现Read方法,以便printFileContents函数可以对其像读取文件一样操作
        next := g()
        if next > 100000 {
            return 0, io.EOF
        }
        //s := fmt.Sprintf("%d
    ", next)
        s := strconv.Itoa(next) + "
    "
    
        return strings.NewReader(s).Read(p)    // 利用strings的NewReader方法来实现Read接口
    }
    
    
    func printFileContents(reader io.Reader) {
        // 从reader中读取内容
        scanner := bufio.NewScanner(reader)
        for scanner.Scan() {
            fmt.Println(scanner.Text())
        }
    }
    
    func main() {
        f := fibonacci()
        printFileContents(f)
    }
  • 相关阅读:
    CodeForces:847D-Dog Show
    CodeForces 699C
    CodeForces:699B-One Bomb
    哈夫曼树:HDU5884-Sort(队列、哈夫曼树)
    Educational Codeforces Round 31- D. Boxes And Balls
    经典:区间dp-合并石子
    Codeforces Round #879 (Div. 2) C. Short Program
    卡顿
    异常断点
    自动布局
  • 原文地址:https://www.cnblogs.com/vincenshen/p/9309562.html
Copyright © 2020-2023  润新知