Encapsulation & Package Exports
Encapsulation in Go is simple and clean. Access visibility is determined entirely by whether a variable, field, or function name starts with a capital letter.
1 Capitalization Visibility Rule
Go does not use access modifier keywords like `private`, `public`, or `protected`. Instead, visibility is managed via naming conventions:
- Exported (Public): Any struct field, function, or variable starting with an **uppercase letter** is exported and visible outside its declaring package (e.g. `fmt.Println`).
- Unexported (Private): Any field or function starting with a **lowercase letter** is private and visible only within its declaring package.
2 Encapsulation Code
Let's look at an example illustrating package structure export boundaries:
Go — Encapsulation
▶ Run Code
package main
import "fmt"
struct BankAccount {
Owner string // Exported (Public)
balance float64 // Unexported (Private to package)
}
func main() {
acc := BankAccount{Owner: "Alice", balance: 500.0}
fmt.Println("Owner: ", acc.Owner)
// Accessing 'balance' is allowed here because this code is in the same package (main).
// If 'BankAccount' was imported from another package, accessing 'balance' would fail.
fmt.Printf("Balance: %.2f\n", acc.balance)
}
3 Code Challenge
Challenge: Write a struct called `Product`. Declare one public field `Name` and one private field `cost`. Inside the package, write a method to initialize these fields and print details. Explain what happens when external packages try to read the `cost` property.