Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Exported vs Unexported Fields | Encapsulation and Interfaces
Struct-Based Design in Go

bookExported vs Unexported Fields

Swipe to show menu

Go uses capitalization as a fundamental mechanism to control the visibility of identifiers, including struct fields and methods. When you define a field or method with a name starting with an uppercase letter, it becomes exported, meaning it is accessible from other packages. Conversely, a name starting with a lowercase letter is unexported and only accessible within the same package. This convention is Go's approach to encapsulation, allowing you to hide internal implementation details and expose only the necessary API surface. Encapsulation is crucial for maintaining clear boundaries in your codebase, preventing unintended dependencies, and enabling safe refactoring.

main.go

main.go

settings/config.go

settings/config.go

copy
1234567891011121314151617
package main import ( "fmt" "example.com/settings" ) func main() { cfg := settings.Config{ AppName: "MyApp", } // Accessing exported field fmt.Println("AppName:", cfg.AppName) // The following line would fail to compile, as dbPassword is unexported: // fmt.Println(cfg.dbPassword) }

When designing backend packages, you should carefully consider which fields and methods truly need to be exported. Exposing only what is necessary keeps your package's API clean and reduces the risk of misuse or breaking changes. By making fields unexported, you can enforce invariants and control how data is accessed or modified, often by providing exported getter and setter methods or dedicated functions. This approach encourages loose coupling between packages and supports maintainable, robust code.

question mark

What is a likely consequence of making all fields in your Go structs exported in a backend package?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 2. Chapterย 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Sectionย 2. Chapterย 1
some-alt