Packages and imports | moakh
Your progress

Code organization · 04

04. Packages and imports

Organize code into packages, control visibility with capitalization, and pull in the standard library.

A Go file always starts with a package declaration. Files in the same directory share one package name. The package named main is the one with the entry point, while every other package is a library.

package main

// This time we're importing two packages from the standard library.
import (
	"fmt"
	"strings"
)

func main() {
	name := strings.ToUpper("maria")

	fmt.Println("Welcome,", name)
}

When you run the program, it will print out the text with the name in uppercase.

$ go run main.go
Welcome, MARIA

Visibility is controlled by the first letter of an identifier. Capitalized names (fmt.Println, strings.ToUpper) are exported and visible to other packages. Lowercase names stay private to their own package.

To make your own package, put files in a subdirectory and give them the same package name:

// menu/menu.go
package menu

func Order(item string) string {
	return "ordered: " + item
}

From main, import it by its module path (the next lesson covers modules) and call menu.Order(...). The directory name and package name usually match. Keep them aligned to avoid confusion.