如何运行一个函数直到返回期望值?

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

How do I run a function until the expected value is returned?

问题

我想运行一个函数,直到它返回0。

value, _ := FuncX()

if value != 0 {
    value, _ := FuncX()
    if(value != 0) {
        value, _ := FuncX()
        if(value != 0) ....
    }
}

这看起来是一种相当丑陋的方法。有没有可能更好的方式?

英文:

I want to run a function until it returns 0.

value, _ := FuncX()

if value != 0 {
    value, _ := FuncX()
    if(value != 0) {
        value, _ := FuncX()
        if(value != 0) ....
    }
}

seems like a pretty ugly way to do it. Whats a possible better way?

答案1

得分: 1

比其他人提供的更复杂的循环头部,尽管循环体中没有任何内容可能会触发编码者的强迫症。

for value, _ := FuncX(); value != 0; value, _ = FuncX() {
}

实际上,这通常是我在Go中逐行读取文件的方式:

// 假设我们已经创建了一个名为buf的bufio.Reader
for line, err := buf.ReadString('\n'); err == nil; line, err = buf.ReadString('\n') {
    // 对行进行处理
}

如果你需要在循环外部使用lineerr,只需预先声明它们,并将:=替换为=

英文:

A more complex loop header than others have offered, although having nothing in the loop body may trigger coder OCD.

for value,_ := FuncX(); value != 0; value,_ = FuncX() {
}

In fact, this is usually how I read files line by line in Go

// Assume we have some bufio.Reader named buf already created
for line,err := buf.ReadString('\n'); err == nil; line,err = buf.ReadString('\n') {
    // Do stuff with the line.
}

If you need line or err outside the loop you just predeclare them and replace the := with =.

答案2

得分: 0

以下是代码的中文翻译:

循环 {
    值, _ := FuncX()
    如果 值 == 0 {
        退出循环
    }
}
英文:
for {
    value, _ := FuncX()
    if value == 0 {
        break
    }
}

答案3

得分: 0

你可以使用如下的循环:

value, _ := FuncX()
for value == 0 {
	value, _ = FuncX() // 注意使用 = 而不是 :=
}
英文:

You can use a loop like:

value, _ := FuncX()
for value == 0 {
	value, _ = FuncX() // note using the = not :=
}

huangapple
  • 本文由 发表于 2014年10月2日 04:58:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/26150553.html
匿名

发表评论

匿名网友

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

确定