提交 5f3f6f15 编写于 作者: _Fighter's avatar _Fighter

2022年1月12日

上级 3a6c218e
package main
import (
"fmt"
"io"
"strings"
)
// 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
func Fibonaccis() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
type intGens struct {
gen func() int
currentReader io.Reader
}
func (g *intGens) Read(
p []byte) (n int, err error) {
err = io.EOF
if g.currentReader != nil {
n, err = g.currentReader.Read(p)
}
if err == io.EOF {
next := g.gen()
s := fmt.Sprintf("%d\n", next)
g.currentReader = strings.NewReader(s)
if n == 0 {
n, err = g.currentReader.Read(p)
}
}
return n, err
}
func main() {
f := &intGens{
gen: Fibonaccis(),
}
for i := 0; i < 20; i++ {
b := make([]byte, 1)
n, err := f.Read(b)
fmt.Printf("%d bytes read: %q. err = %v \n", n, b, err)
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册