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?

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

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; {
      ...
    }

huangapple
  • 本文由 发表于 2021年5月19日 23:21:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/67606142.html
匿名

发表评论

匿名网友

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

确定