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\n", next)
    s := strconv.Itoa(next) + "\n"

    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)
}

 

相关文章:

  • 2021-11-26
  • 2021-07-16
  • 2021-11-12
  • 2023-04-03
  • 2023-03-19
猜你喜欢
  • 2022-01-09
  • 2022-12-23
  • 2021-05-16
  • 2022-12-23
  • 2022-01-19
  • 2021-05-01
  • 2021-05-12
相关资源
相似解决方案