函数调用中的“用作值”


122

在条件语句中评估函数值时,调用函数的正确方法是什么?

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
}

这将返回错误:

./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

您将如何在Go中编写此代码?


2
错误消息会更好:“将void函数调用用作值”或“ ...用作值,但不返回值 ”。
布伦特·布拉德本

Answers:


179

您忘记了声明一个返回值。它应该是:

func sumThis(a, b int) int {
// ...
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.