DEV Community

Cover image for Public vs Private in Go: How Visibility Works (Without public or private)
Caio
Caio

Posted on

Public vs Private in Go: How Visibility Works (Without public or private)

If you come from Java, C#, or TypeScript, you're probably used to writing public and private all the time. In Go, those keywords don't exist. Visibility is defined in a much simpler way: by the first letter of the name.

In this article we'll see how this works in practice, with examples of functions, structs, and methods, along with some best practices.

The golden rule

  • Uppercase letter → exported (public): can be used by other packages.
  • Lowercase letter → unexported (private): can only be used within the same package.

This applies to functions, variables, constants, types, methods, and struct fields.

package example

var Version = "1.0.0"   // public
var debug = false       // private

const MaxItems = 100    // public
const timeout = 30      // private

type User struct{}      // public
type cache struct{}     // private
Enter fullscreen mode Exit fullscreen mode

Public and private functions

Let's create a simple project with the following structure:

myproject/
├── go.mod
├── main.go
└── calculator/
    └── calculator.go
Enter fullscreen mode Exit fullscreen mode

calculator/calculator.go

package calculator

// Sum is public (starts with an uppercase letter): other packages can call it.
func Sum(a, b int) int {
    return validate(a) + validate(b)
}

// validate is private (starts with a lowercase letter): only the calculator package can see it.
func validate(n int) int {
    if n < 0 {
        return 0
    }
    return n
}
Enter fullscreen mode Exit fullscreen mode

main.go

package main

import (
    "fmt"

    "myproject/calculator"
)

func main() {
    fmt.Println(calculator.Sum(2, 3)) // works: 5

    // calculator.validate(5) // compile error
}
Enter fullscreen mode Exit fullscreen mode

If you try to call calculator.validate(5), the compiler complains:

cannot refer to unexported name calculator.validate
Enter fullscreen mode Exit fullscreen mode

In other words, the compiler itself enforces encapsulation. No conventions or code review needed.

Structs, fields, and methods

The same rule applies to struct fields and methods. A very common pattern is to keep the field private and expose access through public methods:

package account

type Account struct {
    Owner   string  // public
    balance float64 // private
}

// NewAccount is a "constructor": the idiomatic way to initialize private fields.
func NewAccount(owner string) *Account {
    return &Account{Owner: owner, balance: 0}
}

// Deposit is a public method.
func (a *Account) Deposit(amount float64) {
    if a.isValidAmount(amount) {
        a.balance += amount
    }
}

// Balance is a public getter to read the private field.
func (a *Account) Balance() float64 {
    return a.balance
}

// isValidAmount is a private method.
func (a *Account) isValidAmount(amount float64) bool {
    return amount > 0
}
Enter fullscreen mode Exit fullscreen mode

Using it from another package:

acc := account.NewAccount("Maria")
acc.Deposit(100)

fmt.Println(acc.Owner)     // ok
fmt.Println(acc.Balance()) // ok: 100

// acc.balance = 1000      // error: unexported field
// acc.isValidAmount(10)   // error: unexported method
Enter fullscreen mode Exit fullscreen mode

Notice that you can't change the balance directly. Every change goes through Deposit, which validates the amount. This protects the data integrity of your struct.

Important points (and gotchas)

1. The unit of privacy is the package

In Go, "private" means private to the package, not to the file or the struct. If two files are in the same folder and declare the same package, they can see each other's private functions.

This is different from Java, where private restricts access to the class.

2. There is no protected

Go has no class inheritance, so the concept of protected doesn't exist. There are only two levels: exported and unexported.

3. Getters don't use the Get prefix

The Go convention is to name the getter for the balance field Balance(), not GetBalance(). Setters, if they exist, are usually named SetBalance().

4. JSON only sees exported fields

This is a classic mistake for beginners. Private fields are not serialized by the encoding/json package:

type Product struct {
    Name  string  `json:"name"`
    price float64 `json:"price"` // will NOT show up in the JSON!
}
Enter fullscreen mode Exit fullscreen mode

If the field needs to appear in an API response, it must start with an uppercase letter:

type Product struct {
    Name  string  `json:"name"`
    Price float64 `json:"price"` // ok
}
Enter fullscreen mode Exit fullscreen mode

The same goes for ORM libraries like GORM: unexported fields are ignored.

5. The internal/ folder

Want to restrict an entire package? Put it inside a folder named internal/. The compiler only allows code from the parent module (or parent directory) to import that package.

Public vs Private in Go: How Visibility Works (Without public or private)

myproject/
├── go.mod
├── cmd/
│   └── api/
│       └── main.go
└── internal/
    ├── handler/
    ├── service/
    └── repository/
Enter fullscreen mode Exit fullscreen mode

Anyone importing your module from outside cannot access anything inside internal/. It's great for hiding implementation details without having to expose everything as public API.

6. Document what's public

Everything exported should have a comment starting with the name of the identifier. go doc and pkg.go.dev use it to generate documentation:

// Sum returns the sum of two integers, ignoring negative values.
func Sum(a, b int) int {
    return validate(a) + validate(b)
}
Enter fullscreen mode Exit fullscreen mode

Best practices

  • Start private. Export only what really needs to be used by other packages. It's easy to make something public later, but making something private again is hard (and breaks compatibility).
  • Keep your public API small. The less you expose, the less you have to maintain and document.
  • Use constructors (NewX) when the struct has private fields that need to be initialized correctly.
  • Use internal/ to organize larger projects into layers without leaking details.

Summary

Characteristic Public (exported) Private (unexported)
Name starts with Uppercase Lowercase
Accessible from Any package Only the same package
Appears in JSON Yes No
Appears in go doc Yes No

Conclusion

Go's approach is minimalist: a single rule, checked by the compiler, with no extra keywords. At first it may feel strange to depend on capitalization, but after a few projects it becomes natural, and the code gets cleaner to read, because you know whether something is public just by looking at its name.

I hope you enjoyed it; if you have any tips, feel free to share them in the comments.

Top comments (0)