Import and Use a Third-Party Package in Golang
The Go programming language has an excellent library of packages that offer a full range of functionality that you can use in your own Go programs.
Mar 28th, 2024 5:00pm by
Feature image via Go.dev.
package main
import "fmt"
func main() {
fmt.Println("Hello, New Stack")
}
nano quote.go
In that file, paste the following:
package main
import "fmt"
import "rsc.io/quote"
func main() {
fmt.Println("Your pithy quote of the day is:\n")
fmt.Println(quote.Go())
}
go mod init quote
Once you’ve done that, you can then download the package with:
go mod tidy
Now, compile your application with:
go build quote.go
This will create an executable named call. Run the app with:
./quote
You’ll see the output I listed above.
Let’s go a bit deeper.
What we’re going to do now is create our own module and then call it from an application.
First, create a new directory structure with the command:
mkdir -p projects/mymodule
Change into the modules directory with:
cd projects/mymodule
Initialize modules with:
go mod init mymodule
You’ll find a new go.mod file has been added.
Next, create a main.go file with:
nano main.go
In that file, paste the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, New Stack!")
}
go run main.go
You should see the following output:
Hello, New Stack!
Great.
Now, we’re going to create a new package that we’ll then call from our main.go file. Still, in the mymodule directory, create a new directory with:
mkdir mypackage
Create a new .go file with:
nano mypackage/mypackage.go
In that file, paste the following:
package newpackage
import "fmt"
func NSHello() {
fmt.Println("Hello, New Stack! You've just called your first module!")
}
nano /main.go
Currently, the file looks like this:
package main
import "fmt"
func main() {
fmt.Println("Hello, New Stack!")
}
import (
"fmt"
"mymodule/mypackage"
)
func main() {
fmt.Println("Hello, New Stack!")
mypackage.NSHello()
}
package main
import (
"fmt"
"mymodule/mypackage"
)
func main() {
fmt.Println("Hello, New Stack!")
mypackage.PrintHello()
}
go run main.go
The output should be:
Hello, New Stack!
Hello, New Stack! You’ve just called your first module!
Or, you can build an executable with the command:
go build main.go
And that is your introduction to calling external packages in Golang.
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don't miss an episode. Subscribe to our YouTube
channel to stream all our podcasts, interviews, demos, and more.