Package Management

Back

Loading concept...

πŸ“¦ Go Package Management: Building Your Code City

Imagine you’re building a LEGO city. Each building has rooms, and each room has stuff inside. Go packages work the same way!


πŸ™οΈ The Big Picture: Your Code is a City

Think of your Go project as a city:

  • The city = your whole project
  • Buildings = packages (folders with Go files)
  • Rooms in buildings = files inside packages
  • Stuff in rooms = functions, types, variables

Why organize? Imagine a city where everything is just thrown in one giant pile. Finding anything would be impossible! Same with code.


πŸ“ Package Organization: Arranging Your City

What It Means

Package organization is how you arrange buildings in your city. Each folder = one package.

Simple Example

myapp/                 ← Your city (project)
β”œβ”€β”€ main.go            ← Front door
β”œβ”€β”€ users/             ← Users building
β”‚   └── users.go
β”œβ”€β”€ orders/            ← Orders building
β”‚   └── orders.go
└── internal/          ← Private area
    └── secrets/
        └── secrets.go

Key Rule

One folder = One package name

All files in the same folder must start with the same package name.

// File: users/users.go
package users  ← Must match folder!

// File: users/helpers.go
package users  ← Same name!

Why This Rocks

  • Easy to find code
  • Easy to share code
  • Easy to test code

🏷️ Package Naming: Naming Your Buildings

The Golden Rules

Think of naming like labeling buildings so everyone knows what’s inside.

βœ… GOOD ❌ BAD Why?
users userPackage Short wins
http HTTP Lowercase only
json jsonParser One word is best
orders order_utils No underscores

Simple Examples

// βœ… Perfect names
package users
package orders
package auth

// ❌ Bad names (don't do this!)
package userManagement   // Too long
package User             // No capitals
package my_package       // No underscores

Memory Trick

Ask yourself: β€œIf I saw this name in 1 second, would I know what it does?”

  • email β†’ Handles emails βœ…
  • emailSendingAndValidationUtilities β†’ Confusing ❌

πŸ‘οΈ Package Visibility: Public vs Private Rooms

The Magic Rule

This is the most important rule in Go:

First Letter Who Can See It? Example
UPPERCASE Everyone (public) User
lowercase Only same building (private) user

Think of It Like…

  • Uppercase = Front door (anyone can walk in)
  • Lowercase = Back room (only people in this building can enter)

Simple Example

package users

// Public - anyone can use this
type User struct {
    Name string
}

// Public - anyone can call this
func CreateUser(name string) User {
    return User{Name: name}
}

// private - only users package can use
func validateName(name string) bool {
    return len(name) > 0
}

πŸ“€ Export Rules: What Leaves the Building

The Export Rules in 30 Seconds

graph TD A["Your Code"] --> B{First Letter?} B -->|Uppercase| C["βœ… EXPORTED<br>Others can use"] B -->|lowercase| D["❌ NOT exported<br>Private to package"]

Everything That Can Be Exported

package shop

// βœ… All EXPORTED (uppercase first letter)
type Product struct{}      // Type
var MaxItems = 100         // Variable
const TaxRate = 0.08       // Constant
func CalculatePrice() {}   // Function

// ❌ All PRIVATE (lowercase first letter)
type helper struct{}       // Type
var maxRetries = 3         // Variable
const secretKey = "abc"    // Constant
func validate() {}         // Function

Inside Structs Too!

type User struct {
    Name  string  // βœ… Public field
    email string  // ❌ Private field
}

Other packages can see user.Name but NOT user.email.


πŸ”’ Internal Packages: The VIP Section

What’s an Internal Package?

Remember our city? Internal packages are like a VIP section that only certain buildings can enter.

myapp/
β”œβ”€β”€ cmd/
β”‚   └── server/
β”‚       └── main.go  ← Can use internal!
β”œβ”€β”€ internal/        ← THE VIP GATE
β”‚   └── secrets/
β”‚       └── secrets.go
└── pkg/
    └── public.go    ← Can use internal!

The Rule

Only packages in the same β€œfamily” can use internal packages.

Example

// File: internal/secrets/secrets.go
package secrets

var ApiKey = "super-secret-123"
// File: cmd/server/main.go
// βœ… This works - we're in the same project
import "myapp/internal/secrets"

func main() {
    key := secrets.ApiKey
}
// File: some-other-project/main.go
// ❌ ERROR! Can't import internal from outside
import "myapp/internal/secrets"  // BLOCKED!

Why Use Internal?

  • Hide messy code
  • Keep implementation details private
  • Allow changes without breaking other projects

πŸ“ Package Documentation: Labels on Your Buildings

Doc Comments = Name Tags

In Go, documentation is just comments right above what you’re describing.

Simple Rules

// Package users handles user accounts.
// It provides functions to create, update,
// and delete users.
package users

// User represents a person in the system.
// Name is required; Email is optional.
type User struct {
    Name  string
    Email string
}

// CreateUser makes a new user with the given name.
// It returns an error if name is empty.
func CreateUser(name string) (*User, error) {
    // ...
}

Documentation Pattern

graph TD A["Package Comment"] --> B["// Package name does..."] C["Type Comment"] --> D["// TypeName is..."] E["Function Comment"] --> F["// FuncName does..."]

Three Golden Rules

  1. Start with the name being documented
  2. Use complete sentences
  3. Put comment directly above (no blank line!)
// βœ… GOOD - starts with function name
// CreateUser makes a new user.
func CreateUser() {}

// ❌ BAD - doesn't start with name
// This function creates a user.
func CreateUser() {}

Run go doc to See Your Docs

go doc myapp/users        # See package docs
go doc myapp/users.User   # See type docs

🎯 Quick Summary

Concept One-Line Rule
Organization One folder = One package
Naming Short, lowercase, no underscores
Visibility Uppercase = public, lowercase = private
Export Rules First letter decides everything
Internal Special folder blocks outside access
Documentation Comment above, start with the name

πŸš€ You’ve Got This!

Remember the city:

  • Organize your buildings (folders)
  • Name them clearly
  • Use CAPS for public doors
  • Put secrets in internal
  • Add labels (docs) so people know what’s inside

Go package management is just common sense organization. If it feels confusing, ask: β€œWould this make sense in a city?”

Happy coding! πŸ™οΈ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.