How to use Go packages?

How to use your own, others’ and Go standard library’s packages?

You can use imported identifiers by using package’s name

For example,fmt package has an exported function,Println. After importing fmt package, you can type: fmt.Println to call the function from fmt library.

Just typing Println will give you an error, because Go will look for Println function inside of your own package instead of fmt package, you need to tell Go specifically that which package’s functions you want to use.


Stdlib packages

Go standard library (stdlib) packages are inside $GOROOT directory and when importing, you don’t need to write full path names for stdlib packages.

What this means is that, you can type: import fmt and then your code can use stdlib'sfmt package.

Standard library packages are available to you after you install Go. You don’t need to download any of them afterwards (or you don’t need to use go get tool to get stdlib packages).

External packages

Other than stdlib packages, there are your own and other people’s packages.

For external packages, you might need to supply the full path to the package.

For example: I created an open-source package, named it as myhttp on Github. This package lets people to easily GET http resources from a specified url with a timeout support. It lives inside this URL: https://github.com/inancgumus/myhttp.

When I want to use myhttp package in my own project, I need to get it first: go get github.com/inancgumus/myhttp, and, then I need to import it: import "github.com/inancgumus/myhttp".

Then, I’d use it like this:

Using an external package.

Here, I’m using myhttp package’s New function with its package name first, and then a dot, and then a New with function’s arguments like: myhttp.New(time.Second).

All packages live inside $GOPATH/src. So, you can import any package from there by typing the package’s directory path except $GOPATH/src.

For example, if a package is under: $GOPATH/src/apackage. You can import it like this: import "apackage".


Non-stdlib packages — Your own packages

You can use the packages that you’ve defined in your own program by supplying a relative path to the package.

For example:import "myprogram/anotherpackage". Here, myprogram is the directory my program resides in, and anotherpackage is the directory inside myprogram directory. I can type this code to import anotherpackage to my current package (which is calling the import).


I’m also creating an online course for Go → Join to my newsletter

“ Let’s stay in touch weekly for new tutorials and tips “


My twitter — @inancgumus — I mostly tweet about Go.