Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Export fields and methods of unexported types #118

Open
abhinav opened this issue Mar 11, 2021 · 0 comments
Open

Proposal: Export fields and methods of unexported types #118

abhinav opened this issue Mar 11, 2021 · 0 comments

Comments

@abhinav
Copy link
Collaborator

abhinav commented Mar 11, 2021

This one will require some careful phrasing but the gist of the proposal is:

For unexported types, it's beneficial to export fields or methods to mark them as part of their "public" API is for use by other unexported types.

As a contrived example,

// counter.go
type countingWriter struct {
    writer io.Writer
    count  int
}

func (cw *countingWriter) Write(b []byte) (int, error) {
    n, err := cw.writer.Write(b)
    cw.inc(n)
    return n, err
}

func (cw *countingWriter) inc(n int) {
    cw.count += n
}

// another.go
func foo(w io.Writer) error {
    cw := &countingWriter{writer: w}
    writeABunch(&cw)
    fmt.Println("wrote", cw.count, "bytes")
}

It would be useful for the author of countingWriter to indicate which fields they intended to be accessed directly, and which are "private". The example above could be:

type countingWriter struct {
    Writer io.Writer
    Count int
}

func (*countingWriter) inc(int)

This indicates that int is for private use but the Writer and Count fields may be accessed freely. If the author wanted to protect writes to Count, maybe they'd switch to:

type countingWriter struct {
    Writer io.Writer

    count int
}

func (*countingWriter) Count() int

Obviously, there's no enforcement and this only works as a general guidance to indicate "publicness" of a field/method of a private type, but as a reader/consumer of a private type in a large package, one might find value in knowing what they should or should not touch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant