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

You can use imported identifiers by using the 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 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:

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).

Alright, that’s all for now. Thank you for reading so far.
Let’s stay in touch:
- 📩 Join my newsletter
- 🐦 Follow me on twitter
- 📦 Get my Go repository for free tutorials, examples, and exercises
- 📺 Learn Go with my Go Bootcamp Course
- ❤️ Do you want to help? Please clap and share the article. Let other people also learn from this article.