Package

Package

In Go (Go), programs are organized into packages. A package is a collection of source files located in the same directory. Functions, types, variables, and constants defined within a specific package can be referenced from any source file within that package.

Public and Private

A package is the smallest unit that can differentiate between public and private access. Every type, function, or constant definition can be exported to make it public, allowing other packages to access it, or it can be declared as private. The way to specify accessibility is by using capitalization. Definitions that start with an uppercase letter are public, while lowercase definitions indicate private access.

models/user.go

package models
 
import "time"
 
type User struct {
	Name         string    // public
	creationDate time.Time // private
}
 
func NewUser(name string) User {
	return User{
		Name:         name,
		creationDate: time.Now(),
	}
}

In the code above, the User type, User.Name field, and NewUser function are public, whereas User.creationDate is private.

main.go

func main() {
	user := models.NewUser("X Jakab")
	fmt.Println(user)
	user.Name = "Y Jakab"
	// user.creationDate = time.Now() // creationDate is private
}

The user.creationDate field cannot be modified outside the models package. Only functions or methods defined within the models package can modify it.