英文:
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 < 10; i++ {
ch <- strconv.Itoa(i)
}
close(ch)
}()
return ch
}
func main() {
for i := range foo() {
fmt.Println(i)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论