Go Packages
Let’s learn about Go packages.
We'll cover the following
Everything in Go is delivered in the form of packages. A Go package is a Go source file that begins with the package
keyword, followed by the name of the package.
Note: Note that packages can have structure. For example, the
net
package has several subdirectories namedhttp
,rpc
,smtp
,textproto
, andurl
, which should be imported asnet/http
,net/mail
,net/rpc
,net/smtp
,net/textproto
, andnet/url
, respectively.
Apart from the packages of the Go standard library, there are external packages that can be imported using their full address, and that should be downloaded on the local machine before their first use. One such example is cobra, which is stored in GitHub.
Purpose and usage
Packages are mainly used for grouping related functions, variables, and constants so that we can transfer them easily and use them in our own Go programs. Note that apart from the main
package, Go packages are not autonomous programs and can’t be compiled into executable files on their own. As a result, if we try to execute a Go package as if it were an autonomous program, we are going to be disappointed:
Get hands-on with 1200+ tech skills courses.