Calling Functions in Conditional Statements
When evaluating the values of functions in conditional statements in Go, the proper way to call them is to declare a return value for the function. Consider the following code:
package main import "fmt" func main() { if sumThis(1, 2) > sumThis(3, 4) { fmt.Println("test") } else { fmt.Println("derp") } } func sumThis(a, b int) { // NOTE: Missing return value return a + b }
Running this code will result in the following errors:
./test4.go:4: sumThis(1, 2) used as value ./test4.go:4: sumThis(3, 4) used as value ./test4.go:11: too many arguments to return
The issue arises because the sumThis function is missing a return value declaration. To fix this, we need to specify the return type of the function, which in this case is an integer (int):
func sumThis(a, b int) int { return a + b }
This modification declares the return value of the function, allowing the conditional statement to properly evaluate the values returned by the sumThis function.
The above is the detailed content of How to Correctly Call Functions in Go's Conditional Statements?. For more information, please follow other related articles on the PHP Chinese website!