Beginner Fundamentals
Packages
Go code is organized into packages. A package is a folder of related .go files that share the same package name.
Declaring a package
Every file starts with its package name. The entry point of a program is package main.
package main
A reusable library would use a descriptive name, like package mathutil.
Importing
Bring in other packages with import. You then use the package name as a prefix.
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("go"))
}
Exported vs unexported
Visibility is controlled by capitalization. An identifier starting with an uppercase letter is exported (public) and usable from other packages. A lowercase name is unexported (private) to its package.
package mathutil
// Exported: usable elsewhere
func Add(a, b int) int {
return a + b
}
// unexported: only inside this package
func subtract(a, b int) int {
return a - b
}
This simple rule replaces keywords like public and private found in other languages.