在函数调用中用作值

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

"used as value" in function call

问题

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

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中编写这段代码?

英文:

What's the proper way of calling functions when evaluating their values in conditional statements?

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 returns 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

How would you write this in Go?

答案1

得分: 228

你忘记声明返回值了。应该是:

func sumThis(a, b int) int {
// ...
英文:

You've forgotten to declare a return value. It should be:

func sumThis(a, b int) int {
// ...

huangapple
  • 本文由 发表于 2012年9月24日 16:13:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/12561162.html
匿名

发表评论

匿名网友

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

确定