Skip to content

docs: say that With keeps field data by reference - #15

Open
ssgreg wants to merge 1 commit into
mainfrom
chore/document-with-references
Open

ssgreg wants to merge 1 commit into
mainfrom
chore/document-with-references

Conversation

@ssgreg

@ssgreg ssgreg commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Problem

Logger.With, logf.With and NewBag keep the field slice, and the data behind Bytes, ByteString, Strings, Ints, Ints64, Floats64, Durations and Group (Ints on 64-bit platforms), by reference. The data is read during encoding, and the built-in encoders may cache and reuse the result. So if the caller changes that data after With, the output depends on what was encoded and cached before:

buf := []byte("abc")
l := logger.With(logf.ByteString("s", buf))
buf[0] = 'Y'
l.Info(ctx, "m")   // "s":"Ybc"

Nothing in the docs says this. The Bag.With doc says "zero copies", but not what that means for the caller.

Change

Documentation only. NewBag describes the contract: the data is kept by reference, read during encoding and possibly cached, so it must not change after it is passed in. Bag.With, Logger.With and logf.With repeat the rule in one line and point to NewBag. Group and the slice-backed field constructors say not to modify the data until the log call returns, or at all once the field is passed to With.

zap's WithLazy also keeps references and evaluates them later; in logf this is how With always works. Copying the data in With was tried in #9 and dropped: it adds work to every With, and reference semantics with a documented contract were chosen instead.

Testing

go build ./... and golangci-lint run pass. No code changes.

Logger.With, logf.With and NewBag keep the fields and the slice and byte data they point to without copying, and the built-in encoders may cache what they encoded, so data changed after With may or may not reach the output. The docs of With, NewBag, Group and the slice-backed field constructors now say so and ask callers not to modify that data.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant