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

bookExported vs Unexported Fields

メニューを表示するにはスワイプしてください

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  5
some-alt