Function Evaluation in Conditional Statements
Conditional statements often require evaluating functions within their conditions. However, the Go programming language imposes specific requirements when attempting to use function calls as values in such statements. To understand this better, consider the following example:
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) { return a + b }
This code snippet attempts to compare the results of two function calls within a conditional statement. However, it fails to compile, producing the following error:
./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 error stems from the absence of a return type for the sumThis function. By omitting the return type, Go interprets the function as returning void. When you then attempt to use the function calls as values in the conditional statement, the compiler finds no return type and treats the calls as used for their side effects rather than their return values.
To resolve this issue, you must explicitly declare a return type for your function. In this case, since the sumThis function returns an integer, its signature should be:
func sumThis(a, b int) int { // ... }
With the correct function signature in place, the code will compile successfully and correctly compare the return values of the function calls within the conditional statement.
The above is the detailed content of How Do I Correctly Use Function Calls in Go's Conditional Statements?. For more information, please follow other related articles on the PHP Chinese website!