duanlu4371
2016-02-25 14:55
浏览 188
已采纳

是否可以使用for循环遍历golang中返回的函数?

Say we have this:

func foo() func() int {
    return func() {
        for i := range [0..10] {
            return i
        }
    }
}

func main() {
    for i := foo() {

    }
}

Can I iterate over the returned function in a for loop without knowing how many times it will loop?

图片转代码服务由CSDN问答提供 功能建议

说我们有这个:

  func foo()func  ()int {
 return func(){
 for i:= range [0..10] {
 return i 
} 
} 
} 
 
func main(){
 for i  := foo(){
 
} 
} 
   
 
 

我可以在for循环中迭代返回的函数,而无需知道它将循环多少次 ?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doubi9531 2016-02-25 15:13
    已采纳

    For example,

    package main
    
    import "fmt"
    
    func foo(n int) func() (int, bool) {
        i := -1
        return func() (int, bool) {
            if i >= n {
                return 0, true
            }
            i++
            return i, false
        }
    }
    
    func main() {
        f := foo(5)
        for i, eof := f(); !eof; i, eof = f() {
            fmt.Println(i)
        }
    }
    

    Output:

    0
    1
    2
    3
    4
    5
    
    打赏 评论
  • doudu4282 2016-02-25 15:12

    You can't iterate over a function alone. A function returns only once, so your for loop would never loop. If you wanted to return a closure over i, you could increment it each call, but you still need a way to know when to stop, which you could do by returning multiple values from the inner function.

    Go also uses channels for communication, which you can range over.

    func foo() chan string {
        ch := make(chan string)
        go func() {
            for i := 0; i < 10; i++ {
                ch <- strconv.Itoa(i)
            }
            close(ch)
        }()
        return ch
    }
    
    func main() {
        for i := range foo() {
            fmt.Println(i)
        }
    }
    

    http://play.golang.org/p/oiFTAgyeJd

    打赏 评论

相关推荐 更多相似问题