语法错误:函数体外的非声明语句

该函数makeEvenGenerator应该返回一个以顺序方式生成偶数的函数:


package main 

import "fmt"

func makeEvenGenerator() func() uint {

    i := uint(0)

    return func() (ret uint) {

        ret = i

        i += 2

        return

    }

}func main() {

    nextEven := makeEvenGenerator()

    fmt.Println(nextEven()) // 0

    fmt.Println(nextEven()) // 2

    fmt.Println(nextEven()) // 4

}  

当我运行它时,我收到错误syntax error: unexpected func, expecting semicolon or newline和Non-declaration statement outside function body.


该代码是从Caleb Doxsey 的An Introduction to Programming in Go 中逐字提取的。我不确定问题是什么。


收到一只叮咚
浏览 340回答 3
3回答

大话西游666

您在末尾的“}”makeEvenGenerator和main.我修复了错误并将代码发布到了操场上。

忽然笑

你失踪之间的新线}在年底makeEvenGenerator和func main。该模式的另一种替代方法是使用不返回函数的通道:func evenGenerator() <-chan uint {&nbsp; &nbsp; ch := make(chan uint)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; i := uint(0)&nbsp; &nbsp; &nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ch <- i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i += 2&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; return ch}func main() {&nbsp; &nbsp; evens := evenGenerator()&nbsp; &nbsp; for i := 0; i < 3; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(<-evens)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go