douhei2002
2018-02-23 13:46 浏览 322
已采纳

Golang中没有返回值函数

While I was reading "the little go" book, I found that it suggests to write a function without any return value. So I proceed to test that function but the program won't compile and give me this "... used as value"error. Anyone knows what is going on here?

package main

import (
    "fmt"
)

func log(message string) {
    fmt.Println(message)
}

func main() {
    msg := log("just a message")
    fmt.Println(msg)
}

I know that this function is trivial (maybe the question is stupid also). But I am just curious to know if this type of function legal in Go?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答 默认 最新

  • 已采纳
    douza9835 douza9835 2018-02-23 13:50

    The function here you have used

    func log(message string){
        fmt.Println(message)
    }
    

    Actually returns nothing.

    But you are assigning it to a variable is incorrect. Since function returns nothing.

    msg := log("just a message")
    

    and that's why the error

    .. used as value

    You can call it directly.

    func main() {
        log("just a message")
    }
    

    Check out on go playground

    点赞 评论 复制链接分享
  • dpleylxzx47207117 dpleylxzx47207117 2018-02-23 13:49

    A function that returns nothing is perfectly valid:

    func log(message string) {
        // .. do stuff
    }
    

    But treating it as though it returns something is invalid:

    msg := log("foo") // what do you expect to be assigned to msg? log() returns nothing!
    
    点赞 评论 复制链接分享
  • duanre1891 duanre1891 2018-02-23 13:51

    Your log() function does not return anything so you can’t assign it result to a variable (msg := ...)

    import(
      "fmt"
       )
    
    func log(message string){
      fmt.Println(message)
    }
    
    func main(){
      log("just a message")
    } 
    
    点赞 评论 复制链接分享

相关推荐