Question

What is a use case for public fields on privat structs in Go

Let's assume the following private struct:

type privateUser struct {
    privateName string
    PublicName string
}

Is there any use for public fields on a private struct? Outside of the package the whole struct is not accessible. Inside the package we can access both fields.

Do I miss something, where is makes a difference for visibility to have a private or public field on a private struct?

 2  57  2
1 Jan 1970

Solution

 4

Reflection allows only to set exported fields (Go Playground).

As Cerise Limón correctly remarks this has an influence how these fields are treated by packages that use reflection, like encoding/json.

Also, when you have a New... function to create this structure in a different package, you can still access the public fields but not create the structure itself. I assume the latter use case is annoying, you probably shouldn't do this.

2024-07-21
eik