In Go, the visibility of variables, functions, structs, and methods is closely related to the case of the first letter:
File example.go:
package mypkg var ExportedVar int // accessible in other packages var unexportedVar int // only in mypkg
When importing a package, you can only refer to exported objects.
Best practice:
Question: "Can a struct with unexported fields be exported? What happens if you try to use such fields in another package?"
Answer: Only the struct with an uppercase letter is exported. All fields of the struct that start with a lowercase letter will be inaccessible outside the package. Trying to access such fields from outside will compile with an error.
Example:
// package user type User struct { Name string // Exported field age int // Not accessible outside package user }
In another package:
u := user.User{Name: "Ivan"} u.age = 42 // Compilation error: age is not accessible
Story
Data loss during JSON marshaling: In the REST API, the struct was exported, but the fields were made unexported (with lowercase letters). As a result, marshal to JSON did not include these fields, and API users did not receive the necessary information.
Story
Access to necessary functions not working: The team moved useful utilities to a separate package but forgot to capitalize their names. The functions remained inaccessible, requiring a redesign of the interfaces.
Story
Name collision during code generation: When generating code in one package, variables with the same names differing only by letter case were used. One of the scripts accidentally renamed the exported constant to a lowercase name. As a result, the application lost global access to this constant, and part of the functionality became unavailable.