I'm a beginner in learning Go, and I'm puzzled by the following two questions:
First:
type S struct{
a func()
b func(i int, j float32, k string)
c *func()
}
func main(){
s := S{c: &func(){}} // Error: Cannot take the address of `func(){}`
}
In this struct, c *func()
is valid, but how can I assigned to it
?
Second:
As I know, functions are first class citizens, so I can pass function as a parameter to another function/method, also I can declare a function variable, so, how does a function value works
, does it's actually a function pointer?
I read some articles about alignment and padding, I know a interface value take up 16 bytes(64-bit system) because a interface value is composed of data pointer and type pointer, what about function value
? I use unsafe.Sizeof(funcValue)
and it returns 8, so I guess it's actually a function pointer. Is there any way to prove it(right or wrong)?
If you want to be able to use the address of a variable that points to this function, you'll need to first assign it to a variable.
package main
type S struct {
a func()
b func(i int, j float32, k string)
c *func()
}
func main() {
c := func() {}
s := S{c: &c} // No error
}
For more information on the inner workings of functions see the language spec.
A function literal can be assigned to a variable or invoked directly.
Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
type S struct{
a func()
b func(i int, j float32, k string)
c *func()
}
But when you are assigning the function to a variable. you are actually taking the address of func
which is not a variable. First assign the function to a variable and then you can assign the address of that variable.
func main(){
s := S{c: &func(){}} // Error: Cannot take the address of `func(){}`
}
The error is:
Error: Cannot take the address of
func(){}
You can only take address of a variable.
package main
import ("fmt")
type S struct{
a func()
b func(i int, j float32, k string)
c *func()
}
func main() {
anonymous := func(){}
temp := S{c: &anonymous}
fmt.Println(temp.c)
}
Check on Playground