Dany
Dany

Reputation: 2800

How to access unexported functions in the same package but from different file

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?

Upvotes: 0

Views: 4301

Answers (1)

icza
icza

Reputation: 418077

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.

Upvotes: 5

Related Questions