douduan1953 2015-10-07 06:24
浏览 113
已采纳

如何在golang的不同文件中访问同一包中未导出的函数?

I am trying to build godoc.org source code in my local to make some changes. My working directory is /Users/Dany/go/src/github.com/golang/gddo. In gddo-server package there several files. One of the go file uses a function from another file which is in the same package but unexported. It is throwing Undefined: <function-name> exception.

Folder is structure is,

golang/gddo/
              gddo-server
                        main.go
                        crawl.go

How do we use unexported function from the same package in a different file? Could anyone help me with this. Also if anyone has any idea about how to build godoc.org code?

  • 写回答

1条回答 默认 最新

  • dongtan7998 2015-10-07 06:34
    关注

    Source files of the same package can refer to identifiers defined in any of the source files without any effort. If they are in the same folder and if they have the same package declaration, you can refer all package-level exported and unexported identifiers as if all would have been defined in one file.

    See Spec: Packages:

    A package in turn is constructed from one or more source files that together declare constants, types, variables and functions belonging to the package and which are accessible in all files of the same package.

    And Spec: Package clause:

    A set of files sharing the same PackageName form the implementation of a package. An implementation may require that all source files for a package inhabit the same directory.

    One thing to note: your example seems to be the special main package. If you want to run it with go run, you have to enumerate all the source files.

    To run your example with go run, navigate to the gddo-server folder and type:

    go run background.go browse.go client.go crawl.go graph.go main.go play.go template.go 
    

    Or simpler if you first build it. Navigate to the gddo-server folder and type:

    go build
    

    This will generate a native executable binary in the same folder. To run it type: gddo-server (on Windows) or ./gddo-server (on Linux).

    Or you can install it with go install which will place the result executable binary in your $GOPATH/bin folder.

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

报告相同问题?

悬赏问题

  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥15 看一下OPENMV原理图有没有错误
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。
  • ¥15 关于哈夫曼树应用得到一些问题