Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Exported vs Unexported Fields | Section
Struct-Oriented Design in Go

bookExported vs Unexported Fields

Stryg for at vise menuen

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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 5

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 5
some-alt