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 idea自动补全键位冲突
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页