英文:
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') {
// 对行进行处理
}
如果你需要在循环外部使用line
或err
,只需预先声明它们,并将:=
替换为=
。
英文:
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 :=
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论