gpt4 book ai didi

Golang : Use one value in conditional from function returning multiple arguments

转载 作者:IT老高 更新时间:2023-10-28 13:02:38 26 4
gpt4 key购买 nike

假设在 Go 中我们有一个返回两个参数的函数

func squareAndCube(int side) (square int, cube int) {
square = side * side
cube = square * side
return
}

那么你想在条件中使用这个函数的第一个(第二个)值:

square, _ := squareAndCube(n)
if square > m {
...
}

但是,如果我们不需要值 square 在其他任何地方使用,我们可以在一行中执行前两行吗?例如

 if squareAndCube(n).First() > m {
...
}

最佳答案

你不能选择多个返回值之一,但你可以写类似

if square, _ := squareAndCube(n); square > m {
// ...
}

square 变量仅在 if 范围内有效。这些“简单语句”可用于if statements , switch statements和其他构造,例如 for 循环。

另见effective go article on if statements .

关于Golang : Use one value in conditional from function returning multiple arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com