普通网友 2018-02-23 13:46
浏览 1051
已采纳

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?