Let's break this down in a very simple, real-world way. We'll use a **bakery **as a metaphor to explain Go modules, packages, imports, and the main package.
๐ Real-World Analogy: A Bakery Shop
๐น Imagine:
- You're running a bakery shop.
- Your shop has multiple departments: Bread, Cakes, Billing, etc.
- Each department has its own set of tools and recipes (code).
- You also sell your baked goods to customers (this is your main service).
๐ฆ 1. What is a Go package?
A package is like a department in your bakery:
- bread โ All code to make bread.
- cake โ All code to make cakes.
- billing โ All code to handle payments.
Each department (package) focuses on a specific job and has its own folder.
// cake/cake.go
package cake
func MakeCake() string {
return "Chocolate Cake"
}
๐ 2. What is a Go module?
A module is your entire bakery business.
Itโs a** collection of all departments (packages)** under one roof.
- 1. A Go module is created with go mod init and has a go.mod file.
- 2. It tells Go: โThis is where my business (code) starts and who I depend on.โ
go mod init github.com/mybakery/shop
This means your bakery's official name is: github.com/mybakery/shop.
๐ 3. What is an import?
An import is when one department wants to use tools from another.
// main.go
package main
import (
"fmt"
"github.com/mybakery/shop/cake"
)
func main() {
fmt.Println("We made:", cake.MakeCake())
}
- Here, the main shop is using the cake department's recipe to make a cake.
- You use import to pull in the code you need from other packages (your own or third-party).
๐ง 4. What is the main package, and why is it mandatory?
The main package is the front counter of your bakery.
- This is where customers walk in and interact with your shop.
- In Go, the program starts execution from the main package, specifically the main() function.
// main.go
package main
func main() {
// Entry point: This is where Go starts running your program
}
If there's no main package, it's like a bakery with no front counter. It has great recipes, but nobody knows how to start using them!
โ Summary
๐กReal Example
Youโre building a tool that:
- Has maths functions (addition, subtraction).
- Shows results from the main program.
File: go.mod
module github.com/mytools/calc
File: maths/add.go
package maths
func Add(a, b int) int {
return a + b
}
File: main.go
package main
import (
"fmt"
"github.com/mytools/calc/maths"
)
func main() {
sum := maths.Add(3, 4)
fmt.Println("Sum is:", sum)
}
Top comments (0)