老师这节课里为啥我的代码执行会失败。。求教
来源:7-2 函数式编程例一

weibo_留下的四糸乃_0
2022-08-28
package main
import (
"bufio"
"fmt"
"io"
"strings"
)
func fba() func() 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() {
f := fba()
printFileContents(f)
}
以下是报错
# command-line-arguments
.\main.go:12:9: cannot use func literal (type func() int) as type func() intGen in return argument
.\main.go:38:19: cannot use f (type func() intGen) as type io.Reader in argument to printFileContents:
func() intGen does not implement io.Reader (missing Read method)
实在是找不到问题所在,我用的go1.13.3,vscode编辑器。
写回答
1回答
-
ccmouse
2022-09-05
第一条错:cannot use func literal (type func() int) as type func() intGen in return argument
它说不能用type func() int来当作type func() intGen来使用。是的。
return func() int { a, b = b, a+b return a }
这里返回的是func() int,但是函数申明里是func() intGen。应该是:
func fba() intGen
00
相似问题