For example, as of Go 1.24, https://pkg.go.dev/crypto/rand#Read always returns a nil error on all platforms, so any callers like

_, err := rand.Read(b[:])
if err != nil {
        return nil, err
}

can be modernized and simplified to just

rand.Read(b[:])

I'm sure there are other instances where standard library APIs can never fail. Another one that comes to mind is the various io.Reader and io.Writer methods on bytes.Buffer, or some of the methods on strings.Builder.

Comment From: prattmic

How does the tool decide which functions can never return an error? Hardcoded list? Special comment? Hyrum’s law assumption that anything that doesn’t return an error today can never add one?

Comment From: adonovan

Although an optimizing compiler is free to exploit all its knowledge of the implementation of any function when generating object code, a source-level transformation tool is not, since we don't want to make persistent code changes based on ephemeral facts about the code as it is today.

However, if we had an annotation that asserts that the result is always (or never) zero, then an analyzer could apply "assumes/guarantees" reasoning; that is https://github.com/golang/go/issues/65984.

I'm sure there are other instances where standard library APIs can never fail. Another one that comes to mind is the various io.Reader and io.Writer methods on bytes.Buffer, or some of the methods on strings.Builder.

In certain places such as the ignoredError Inlay Hint, we use a hardcoded list of functions that "can't fail", where ideally we we would allow users to annotate arbitrary functions in that way (and check their consistency).

I don't think this feature is feasible without an annotation, so I'm closing this as a dup of https://github.com/golang/go/issues/65984.