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

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?

图片转代码服务由CSDN问答提供 功能建议

当我在阅读“小小的忙”一书时,我发现它建议编写一个没有任何返回值的函数 。 因此,我继续测试该功能,但程序无法编译,并给我这个“ ...用作值”错误。 有人知道这是怎么回事吗?

 包main 
 
import(
“ fmt” 
)
 
func log(消息字符串){
 fmt  .Println(message)
} 
 
func main(){
 msg:= log(“只是一条消息”)
 fmt.Println(msg)
} 
    
 
 

我知道此功能很简单(也许问题也很愚蠢)。 但是我只是想知道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条)

相关推荐 更多相似问题