drbmhd9583 2018-08-24 06:26
浏览 64
已采纳

功能如何运作

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

  • 写回答

2条回答 默认 最新

  • dpb_4431 2018-08-24 06:33
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端