Packages

// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.

project/
├── go.mod
└── package
    ├── source.go
    └── subPackage
        └── source.go

The first statement in any go file is a package declaration., followed by import, then package level members such as variables, constants and functions:

package user

import "fmt"

Go supports two levels of visibility, package and public, if the the first letter of a thing is a capital it means it has public visibility. Lowercase naming implies private visibility.

There are two levels of viability:

  • package
  • public

For example, importing the following user package the ID and Username can be seen but the password would remain private within the package.

package user

type User struct {
    ID          int
    Username    string
    password    string
}

Example:

.
└── sandbox
    ├── go.mod
    ├── main.go
    └── settings
        └── settings.go
main.gogo
package main

import (
	"fmt"

	"sandbox/settings"
)

func main() {

	message := settings.MessageOfTheDay()
	fmt.Println(message)
}
settings/settings.gogo
package settings

import (
	"os"
)

func MessageOfTheDay() (motd string) {

	if len(os.Getenv("MOTD")) == 0 {
		os.Setenv("MOTD", "Hello World!")
	}

	motd = os.Getenv("MOTD")

	return
}