1. 程式人生 > >Go 語言為Fibonacci函數實現Read方法

Go 語言為Fibonacci函數實現Read方法

實現 import col code 利用 pre string for nts

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

Go 語言為Fibonacci函數實現Read方法