ProgrammingMiddle/Lead Go Developer

Tell us about the features of working with packages and visibility in Go. When and how should exported and unexported objects be used?

Pass interviews with Hintsage AI assistant

Answer

In Go, the visibility of variables, functions, structs, and methods is closely related to the case of the first letter:

  • If the name starts with an uppercase letter — the object is exported outside the package.
  • If the name starts with a lowercase letter — the object is only accessible within its own package.

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:

  • Hide implementation details, export only necessary types and functions.
  • Use lowercase names for private constants/functions.

Trick question

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

Examples of real errors from practice


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.