Go Packages, Modules, and Concurrency
March 13, 2025In my previous post, I wrote a simple program. Now, let’s take the next steps by exploring Go’s package system, module management, and concurrency features.
Go Packages
Go code is organized into packages. A package is a collection of related Go source files. The main
package is special because it defines an executable program.
To create and use a package:
- Inside your project, create a new folder called
greetings
:mkdir greetings
- Create a file
greetings/greetings.go
:package greetings import "fmt" func Hello(name string) string { return fmt.Sprintf("Hello, %s!", name) }
- Use this package in
main.go
:package main import ( "fmt" "my-go-project/greetings" ) func main() { message := greetings.Hello("Kostas") fmt.Println(message) }
- Run the program:
Expected output:
go run main.go
Hello, Kostas!
Go Modules
Go modules simplify dependency management. If you haven’t initialized a module yet, do it with:
go mod init my-go-project
To add third-party packages, use go get
. For example:
go get github.com/fatih/color
Now, you can use this package in your code:
package main
import (
"fmt"
"github.com/fatih/color"
)
func main() {
color.Cyan("This is a colored message!")
}
Run the program, and you’ll see colored output!
Go Concurrency
One of Go’s strengths is its built-in support for concurrency using goroutines and channels.
Goroutines
A goroutine is a lightweight thread managed by Go.
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine!")
}
func main() {
go sayHello() // Start a goroutine
time.Sleep(time.Second) // Wait to see the output
fmt.Println("Main function finished")
}
Channels
Channels allow goroutines to communicate safely.
package main
import "fmt"
func main() {
messages := make(chan string)
go func() {
messages <- "Hello from goroutine!"
}()
fmt.Println(<-messages) // Receive and print message
}