In Golang if I am calling a func inside fmt.Println(someName) without () then also there is no error but it is printing some hashcode. Why so?

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

In Golang if I am calling a func inside fmt.Println(someName) without () then also there is no error but it is printing some hashcode. Why so?

问题

这可能是一个愚蠢的问题,但我对Golang还不熟悉,所以尝试了一些代码更改以便理解。

我创建了一个如下所示的函数:

   func main() {
	    fmt.Println(foo)
    }
    func foo() int {
  	    return 10
    }

fmt.Println(foo)中,调用foo时,我没有使用括号(通常我们会像foo()这样调用函数)。
但是它没有报错/异常,而是打印了一些哈希码,例如0x10458bda0,并且每次调用时都会发生变化。所以我想知道为什么会打印哈希码?在Go中,函数是否也是临时存储在某个内存中,并返回该地址。

英文:

This may be a silly Question but I am new to Golang. so was trying with some code changes just to understand.
I created a func as shown below:

   func main() {
	    fmt.Println(foo)
    }
    func foo() int {
  	    return 10
    }

In fmt.Println(foo) while calling foo, I am not giving () (normally we call func like foo()).
But it is not giving any error/exception, in return it is printing some hashcode like 0x10458bda0
and for every call it is getting changed. so just want to know why it is printing hash? In go are functions also temporarily stored in some memory and returning that address.

答案1

得分: 3

Golang将函数存储在内存中,并将函数传递给fmt.Println(),例如fmt.Println(foo)将打印该函数在内存中的地址。每次调用fmt.Println(foo)时,该地址不会改变。另一方面,如果将函数调用传递给fmt.Println(),例如fmt.Println(foo()),函数foo()将首先被执行,然后打印其返回值。

英文:

Golang stores the functions somewhere in the memory and passing a function to fmt.Println(), e.g., fmt.Println(foo) will print the address of that function in memory. That address does not change for every call to fmt.Println(foo). On the other hand, if you passed a function call to the fmt.Println(), e.g., fmt.Println(foo()), the function foo() will be executed first and its return value will be printed.

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

发表评论

匿名网友

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

确定