一个函数是如何工作的
How does a function works
我是初学围棋的人,对以下两个问题很疑惑:
第一个:
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(){}`
}
在此结构中,c *func()
有效,但 how can I assigned to it
?
第二:
据我所知,函数首先是class公民,所以我可以将函数作为参数传递给另一个function/method,我也可以声明一个函数变量,所以,how does a function value works
,它实际上是一个函数指针?
看了一些关于alignment和padding的文章,我知道一个接口值占用16个字节(64位系统),因为一个接口值是由数据指针和类型指针组成的,what about function value
?我使用 unsafe.Sizeof(funcValue)
而它是 returns 8,所以我猜它实际上是一个函数指针。有没有办法证明(对错)?
如果您希望能够使用指向此函数的变量地址,您需要先将其分配给一个变量。
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
}
有关函数内部工作原理的更多信息,请参阅 language spec。
函数字面量可以赋值给变量或直接调用。
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()
}
但是当您将函数分配给变量时。您实际上正在获取 func
的地址,这不是变量。先把函数赋值给一个变量,然后你就可以赋值那个变量的地址了。
func main(){
s := S{c: &func(){}} // Error: Cannot take the address of `func(){}`
}
错误是:
Error: Cannot take the address of func(){}
你只能取一个变量的地址。
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)
}
查看 Playground
我是初学围棋的人,对以下两个问题很疑惑:
第一个:
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(){}`
}
在此结构中,c *func()
有效,但 how can I assigned to it
?
第二:
据我所知,函数首先是class公民,所以我可以将函数作为参数传递给另一个function/method,我也可以声明一个函数变量,所以,how does a function value works
,它实际上是一个函数指针?
看了一些关于alignment和padding的文章,我知道一个接口值占用16个字节(64位系统),因为一个接口值是由数据指针和类型指针组成的,what about function value
?我使用 unsafe.Sizeof(funcValue)
而它是 returns 8,所以我猜它实际上是一个函数指针。有没有办法证明(对错)?
如果您希望能够使用指向此函数的变量地址,您需要先将其分配给一个变量。
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
}
有关函数内部工作原理的更多信息,请参阅 language spec。
函数字面量可以赋值给变量或直接调用。
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()
}
但是当您将函数分配给变量时。您实际上正在获取 func
的地址,这不是变量。先把函数赋值给一个变量,然后你就可以赋值那个变量的地址了。
func main(){
s := S{c: &func(){}} // Error: Cannot take the address of `func(){}`
}
错误是:
Error: Cannot take the address of
func(){}
你只能取一个变量的地址。
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)
}
查看 Playground