fib 那一节一直提示cannot use f (type func() int) as type io.Reader

来源:7-2 函数式编程例一

慕工程9243709

2020-03-04

我已经实现了 reader 接口, 但还是提示这个, 下面是我的代码

package main

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

func fibonacci() intGen {
	a, b := 0, 1
	return func() int {
		a, b = b, a+b
		return a
	}
}

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)
	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
	f = fibonacci()
	printFileContents(f)
}

写回答

1回答

ccmouse

2020-03-07

应该是

type intGen func() int

不能有=

有了=它就没有把intGen当作一个新的类型来处理

1
0

Google资深工程师深度讲解Go语言 由浅入深掌握Go语言

语法+分布式爬虫实战 为转型工程师量身打造

5995 学习 · 1909 问题

查看课程