Page Content

Tutorials

What Are Packages In Go And How To Declare Packages

Go uses packages as a basic way to organize and reuse code, which promotes the “Don’t Repeat Yourself” philosophy and good software engineering practices. For programs to be reliable, maintainable, and effective, they are essential.

What are packages in Go?

A package declaration and are located in the same directory is called a package. Everything in Go is provided in packages, which bundle together variables, constants, and related functions for convenient transfer and usage in other Go programs.

Purposes of Bundling Code in Packages

Reduces Naming Conflicts: Function names can be brief and to the point by dividing code into discrete packages, which lessens the likelihood of overlapping names.

Organizes Code: Code is easier to locate and manage with packages, especially in larger projects.

Speeds Up Compilation: Important development time is saved because the compiler only needs to recompile fewer portions of a program.

Code Reusability: An effective way to share functionality within an application or with other apps is through packages.

Package Declaration

A package declaration is a prerequisite for all Go programs. This statement specifies the code bundle to which the file is assigned. Packages must declare the same package name, and each folder can only contain one package.

Executable Programs: Package main is required for programs that may be executed straight from the terminal (or that end in.exe on Windows). Program execution begins with the main() function, which is found in the main package. If a package is not main, you cannot run it.

Libraries: Package math is one of the descriptive names declared by packages that are used to reuse code in other programs (libraries).

Example of package main in a “Hello, World!” program:

package main
import "fmt"
func main() {
    fmt.Println("Hello, World")
}

Output

Hello, World

Importing Packages

You can use the import keyword to incorporate code from other packages into your program. A package’s functions, variables, and types are made available in your current program when you import it.

Standard Library Packages: Go offers a comprehensive standard library that includes numerous pre-built packages for a variety of functions, including math/rand (for random numbers), os (for operating system operations), net/http (for web services), and fmt (for formatted input/output).

Third-Party Packages: The go get command downloads packages from repositories such as GitHub and installs them in your GOPATH/src directory. This allows you to install packages created by other developers. For these packages, the import path usually contains the entire repository path, such as github.com/digitalocean/godo.

Dot Notation: It is necessary to prefix a function or variable from an imported package with the package name and a dot (for example, fmt.Println or os.Args).

Strictness of Imports: Because of its strictness, the Go compiler will not compile if you import a package but do not utilise it or if any packages are missing. In this way, needless compilation lags are avoided.

Package Aliases: When importing packages, you can establish an alias if you need to import two packages with the same name or just want a shorter name. As an example:

Formatting Imports: Automatic import block formatting is possible using tools like goimports, which usually organise standard library packages first, then third-party packages, with blank lines separating them.

Creating Your Own Packages

A directory named after the package contains the source files needed to develop a bespoke package.

Example: Creating a math package:

  • Create a folder structure: ~/Go/src/golang-book/chapter11/math
  • Create math.go inside ~/Go/src/golang-book/chapter11/math:
  • Create main.go in ~/Go/src/golang-book/chapter11 to use it:
  • Install the custom package: Open the math folder (/Go/src/golang-book/chapter11/math) in your terminal, then type go install. Math.go is compiled, and a linkable object file is produced.
  • Run the main program: To execute go run main.go, navigate to the chapter11 folder (~/Go/src/golang-book/chapter11). 2.5 ought should appear as the outcome.

Package Visibility (Exported vs. Unexported)

The identifiers (functions, variables, types, constants, struct fields, and methods) that are exposed outside of its package are determined by a straightforward rule in Go:

  • A package can see an c that begins with an uppercase letter since it is exported (public).
  • When an identifier begins with a lowercase letter, it is only visible within the package in which it was defined and is not exportable (private).

Because it enables developers to conceal internal implementation details and only reveal the essential components of a package, this approach is essential for encapsulation and sound API design. By doing this, the possibility of disrupting external code during internal modifications is reduced.

You would get a compile-time error like “cannot refer to unexported name logging.debug” if a main package attempted to access logging.debug directly.

Documentation

Comments in the source code can be used by Go to automatically create package documentation.

  • Just before a declaration, comments that start with // are regarded as that item’s documentation.
  • The godoc utility can be run from the terminal (godoc <package_path> <function_name>) or as a web server (godoc -http=":6060") to browse documentation locally.

Example of adding documentation:

// Finds the average of a series of numbers
func Average(xs []float64) float64 { // ...

Running godoc golang-book/chapter11/math Average would display this comment along with the function signature.

Testing

Go includes a unique tool called go test that makes it easier to write package tests.

  • Test files are identified by their _test.go suffix, and functions that begin with Test (such as TestAverage) are considered tests.
  • To ensure the code is reliable and of high quality, go test will search for and execute tests in the current folder.

Core Packages

Real-world software mainly uses pre-existing libraries rather than creating everything from scratch. A large number of frequently used packages are included in Go’s standard distribution. Among these are:

strings: Functions for working with strings and other UTF-8 data.consists of strings.ChangeAll.

io / ioutil: To do input/output tasks, such as reading and writing documents and folders.

fmt: Implements input and output formatting, including terminal printing.

errors: To handle and create unique error kinds.

container: Provides data structures like doubly-linked lists (container/list), heaps (container/heap), and rings (container/ring).

hash / crypto: Both cryptographic and non-cryptographic hash functions are covered.

net / net/http / net/rpc: Remote Procedure Calls (RPC), HTTP servers, and TCP are examples of network programming.

flag: For deciphering flags and command-line parameters.

sync / sync/atomic: For conventional primitives for synchronisation and multithreading.

time: For discussing dates and times.

Additionally, the Go compiler carries out error checking, identifying problems such as invalid operations, missing imports, and unused variables throughout the build process, greatly increasing the efficiency of development.

You can also read Context Package With Timeouts And Deadlines In Go Language

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index