duanci8209 2013-08-02 09:35
浏览 73
已采纳

在go包中公开一个函数

I would like to expose a function directly from a package.
So I could call my package directly instead of mypackage.Somepublic() method.

package main

import (
    "mypackage"
    "fmt"
)

func main() {
    var result = mypackage() 
    fmt.Println(result)    
}

In node.js, for example, you can expose a anonymous function

module.export = function() {
    console.log('ta da!');
}

or an object

module.export = {  
    doMagic: function() {  
        console.log('ta da!');
    }
};
  • 写回答

4条回答 默认 最新

  • dongre6270 2013-08-02 14:22
    关注

    While there is no direct analogy for your Node.js example, what you can do in Go is something called a "local import." Basically, a local import imports all of the items - functions, types, variables, etc - that a package exports into your local namespace so that they can be accessed as if they had been defined locally. You do this by prefacing the package name with a dot. For example:

    import . "fmt"
    
    func main() {
        Println("Hello!") // Same as fmt.Println("Hello!")
    }
    

    (See this in action).

    This will work for any item that fmt exports. You could do a similar thing with mypackage (this is modified from the code you posted):

    package main
    
    import (
        . "mypackage"
        "fmt"
    )
    
    func main() {
        var result = Somepublic() // Equivalent to mypackage.Somepublic()
        fmt.Println(result)    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

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