Structuring Go projects/code
Like other programming languages, Go has its own approach to organizing code.
Package
The smallest unit for organizing code in Go is a package. A package is constructed from one or multiple source files, each containing distinct functionality for easy maintenance.
Each source file begins with a 'package' clause to encapsulate the code within the package. Compiled packages can be imported into other package's source code for code reuse.
The 'main' package serves as the entry point for program execution."
Example: Continue the exercise from part 1 of this series Mastering Go: Part 1 - Getting Familiar
The following example demonstrates how to format dates using the 'dateformater' package and format person names and addresses using the 'stringformater' package.
Step 1: Create a folder named 'date_formater' within the 'LearnGo' directory and add a Go file named 'date_formater.go'.
Copy the code below into the 'date_formater.go' file.”
package dateformater
type Date struct {
Year string
Month string
Day string
}
func (d *Date) Format() string {
return d.Month + "/" + d.Day + "/" + d.Year
}
Step 2: Create a new folder named 'string_formater' within the 'LearnGo' directory and add a file named 'name_formater.go'.
Paste the code provided below into the 'name_formater.go' file.
package stringformater
type PersonName struct {
FirstName string
LastName string
}
func (rawName *PersonName) Format() string {
return rawName.FirstName + " " + rawName.LastName
}
Step 3: Add a new file named 'address_formater.go' within the 'string_formater' folder. Paste the code below into the 'address_formater.go' file."
package stringformater
type Address struct {
StreetNumber string
StreetName string
City string
State string
Zip string
}
func (a *Address) Format() string {
return a.StreetNumber + " " + a.StreetName + ", " + a.City + ", " + a.State + " " + a.Zip
}
Step 4: Now, modify the 'my_first_go.go' file and add the following code:
package main
import (
dateformater "LearnGo/date_formater" // import data formater package
stringformater "LearnGo/string_formater" // import string formater package
"fmt"
)
func main() {
fmt.Println("Import date format package!")
dateformater := dateformater.Date{Year: "2021", Month: "07", Day: "01"}
fmt.Println(dateformater.Format())
fmt.Println("Use name format package to format name!")
nameFormater := stringformater.PersonName{FirstName: "Sharad", LastName: "Subedi"}
fmt.Println(nameFormater.Format())
fmt.Println("Use name format package to format billing address!")
addressFormater := stringformater.Address{StreetNumber: "123", StreetName: "Main St", City: "San Francisco", State: "CA", Zip: "94101"}
fmt.Println(addressFormater.Format())
}
Now, you have successfully imported and utilized the functions encapsulated within different packages into the “main” package. Below is the project folder structure.
In the above example, the code is separated into different packages based on their functionality and use cases. If you are familiar with C#, you can relate the C# namespace to the Golang package.
Module
A Go module is a collection of packages that are related to a set of functions serving a specific purpose. For example, we can create a Go module to support file read and write operations. Any other program or module that needs to read and write files can utilize that module.
Go generates the go.mod file when you run the go mod init command. Execute the below command in the VS code terminal to generate go.mod file.
$ go mod init learngo
The module file contains
- name of the module
- version of the go required to run the module
Example: Continuation of the previous section (Package)
In this exercise, we will reorganize the above code with multiple modules.
Step 1: Create a new folder named 'main' and move the 'my_first_go.go' file into it. Rename the file to 'main.go'.
Step 2: Run the module initialization command to generate individual modules for 'main', 'date_formater', and 'string_formater'. Make sure to change the directory path before executing the 'go mod init' command.
Commands:
$ go mod init learngo/main $ go mod init learngo/string_formater
$ go mod init learngo/date_formater
Step 3. Edit the go.mod file in the main directory. you can use the below command to edit
$go mod edit -replace learngo/date_formater=../date_formater
$go mod edit -replace learngo/string_formater=../string_formater
Step 4. Synchronize the dependencies
To synchronize and Add required dependencies of the module, we need to run the command:
$ go mod tidy
Command result:
go: found learngo/date_formater in learngo/date_formater v0.0.0-00010101000000-000000000000
go: found learngo/string_formater in learngo/string_formater v0.0.0-00010101000000-000000000000
If the required dependencies are not being created, then run the below command to create dependencies:
$go get learngo/date_formater
$go get learngo/strig_formater
For specific code or module versioning, update the default created version number with your module version
Step 6. Run the main module.
command: $ go run .
In the above screenshot, note the content of the 'main/go.mod' file and observe how modules are referenced and used. Additionally, remember the folder structure of the project for better organization of your Go projects.
Congratulations! You have completed part 2 of the Go programming language learning series. You've learned how to structure code using packages, modules, and basic naming standards of the Go language. Follow this blog for more exciting and industry-standard Go programming concepts.
Reference:
Excellent tips for structuring Go projects cleanly.
ReplyDeleteEasy to read. Nicely explained.
ReplyDelete