Go Packages and Imports

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


Today, we’re going to talk about Go packages and imports. Understanding how packages and imports work is essential for writing efficient and modular code in Go, so let’s dive right in.

In Go, a package is simply a collection of related functions, types, and variables. A package can be used by other packages or programs by importing it.

Now, I know what you’re thinking: “Joel, Richard, how do we import packages in Go?” Well, let’s take a look at an example.

Suppose we have a package called “math” that contains some mathematical functions that we want to use in our program. To use this package, we need to import it into our program:

package main

import "math"

func main() {
    x := math.Sqrt(16)
    fmt.Println(x)
}

In this example, we import the “math” package using the import statement. We can then use the functions in the math package, such as the Sqrt function, by prefixing them with the package name.

Go also supports importing multiple packages in a single import statement:

import (
    "fmt"
    "math"
)

In this example, we import both the fmt and `math" packages in a single import statement.

Now, let’s talk about how to create and use your own packages in Go. To create a new package, simply create a new directory with the same name as the package, and create one or more Go source files within that directory. For example, let’s create a new package called “utils” that contains some utility functions:

utils/
    utils.go

In the utils.go file, we’ll define some functions that we want to use in our main program:

package utils

func SayHello() {
    fmt.Println("Hello, world!")
}

func Sum(x int, y int) int {
    return x + y
}

Now, to use these functions in our main program, we need to import the “utils” package:

package main

import "utils"

func main() {
    utils.SayHello()
    x := utils.Sum(10, 20)
    fmt.Println(x)
}

In this example, we import the “utils” package and use its SayHello and Sum functions.

And that’s it for understanding Go packages and imports! With this knowledge, you should be able to create and use your own packages, as well as import and use packages from others. Thanks for reading, and happy coding!

Stay curious and always keep learning.



Stay up to date on the latest in Coding for AI and Data Science

Intuit Mailchimp