douzhaolu4780 2018-01-25 14:46
浏览 80
已采纳

转到另一个包中的函数定义

I am reading this post about time.startTimer declaration and definition.

From the answer, time.startTimer is declared in src/time/sleep.go as follows:

func startTimer(*runtimeTimer)

And its definition is in src/runtime/time.go as follows:

func startTimer(t *timer) {
    if raceenabled {
        racerelease(unsafe.Pointer(t))
    }
    addtimer(t)
}

So it seems that you can declare a function in one .go file and implement it in another .go file. I tried the same way, for example, declare a function in a.go and implement it in b.go, but it always failed when go run a.go. Is that the correct way to do so? How can I declare a function that is implemented in another .go file? There is no import in either sleep.go or time.go. How does Go do it?

Thanks

  • 写回答

1条回答 默认 最新

  • duang8642 2018-01-25 14:52
    关注

    If you look on the line above the startTimer body, you will see a special directive for the go compiler:

    //go:linkname stopTimer time.stopTimer
    

    From the compile command documentation

    //go:linkname localname importpath.name
    

    The //go:linkname directive instructs the compiler to use “importpath.name” as the object file symbol name for the variable or function declared as “localname” in the source code. Because this directive can subvert the type system and package modularity, it is only enabled in files that have imported "unsafe".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度