在Go语言中,可以使用for循环迭代返回的函数吗?

huangapple go评论73阅读模式
英文:

Is it possible to iterate over a returned function in golang with a for loop?

问题

我们假设有以下代码:

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

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

我能在不知道循环次数的情况下,通过for循环迭代返回的函数吗?

英文:

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?

答案1

得分: 5

例如,

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)
    }
}

输出:

0
1
2
3
4
5
英文:

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

答案2

得分: 1

你不能单独迭代一个函数。函数只返回一次,所以你的for循环永远不会循环。如果你想返回一个闭包来包含i,你可以在每次调用时递增它,但你仍然需要一种知道何时停止的方法,你可以通过从内部函数返回多个值来实现。

Go语言还使用通道进行通信,你可以使用range来遍历通道。

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)
    }
}

点击这里查看示例代码。

英文:

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 &lt; 10; i++ {
			ch &lt;- strconv.Itoa(i)
		}
		close(ch)
	}()
	return ch
}

func main() {
	for i := range foo() {
		fmt.Println(i)
	}
}

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

huangapple
  • 本文由 发表于 2016年2月25日 22:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/35630747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定