英文:
How do I use a local variable and a temporary variable in a for loop to receive two return values from a function in go?
问题
func TwoResults() (int, int) {
return 0, 0
}
func ForStructure() int {
var a int
for a, b := TwoResults(); a == 0 && b == 0; {
return b
}
return a
}
在ForStructure
函数中,我想声明一个局部变量,并在for
循环中使用它来接收TwoResults
函数的一个值。同时,我使用一个临时变量来接收另一个值。
但是我只能使用:=
,这将一个变量变成一个临时变量。
另外,我不想改变我的代码,像这样:
func ForStructure() int {
var a int
for _, b := TwoResults(); a == 0 && b == 0; {
return b
}
a, _ = TwoResults()
return a
}
英文:
func TwoResults() (int, int) {
return 0, 0
}
func ForStructure() int {
var a int
for a, b := TwoResults(); a == 0 && b == 0; {
return b
}
return a
}
In ForStructure function, I'd like to declare a local variable and use it to receive one value from the TwoResults function in the for loop. At the same time, I use a temporary variable to receive another value.
But I can only use ":=" , this turns a variable into a temporary variable.
Also, I don't want to change my code like this:
func ForStructure() int {
var a int
for _, b := TwoResults(); a == 0 && b == 0; {
return b
}
a, _ = TwoResults()
return a
}
答案1
得分: 2
你可以将代码修改为以下形式:
var a int
var b int
for a, b = TwoResults(); a == 0 && b == 0; {
return b
}
return a
英文:
You can change your code like this instead:
var a int
var b int
for a, b = TwoResults(); a == 0 && b == 0; {
return b
}
return a
答案2
得分: 1
声明两个变量并使用=
:
var a, b int
for a, b = TwoResults(); a == 0 && b == 0; {
...
}
声明两个变量并使用=
:
var a, b int
for a, b = TwoResults(); a == 0 && b == 0; {
...
}
英文:
Declare both variables and use =
:
var a,b int
for a, b = TwoResults(); a == 0 && b == 0; {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论