Description
Context
Heap allocations are almost unavoidable in Go. Most of the language has been designed around having an excellent garbage collector. That said, there is a growing interest in being more mindful of how we allocate memory. See proposals #51317 (arenas) #71497 (json/v2). The embedded Go community is also gaining traction as powerful compute becomes more available on small devices such as the recent RP2350 MCU, which was quickly supported by TinyGo due to widespread community driven effort by new contributors.
One of the more common methods of allocating memory in Go is through the fmt.Stringer interface which permeates a big part of the Go ecosystem. Most of the time it is invisible, used from inside fmt.Print*
family of functions. This method serves a very important purpose in Go which is to give a text visual of a data structure or concept abstracted by a data structure.
The issue with this interface is that when the string is not constant and must be built it allocates, always. This presents an issue for developers seeking to minimize or constrain allocations. For sure if some of these developers were given a fmt.Stringer
interface which constrains allocations they would prefer it to the current fmt.Stringer
interface.
Proposal
I propose we add a fmt.StringAppender
interface with the following signature:
type StringAppender interface {
StringAppend([]byte) []byte
}
The method would do what one would expect, append the string representation to the buffer and return the extended result, just like the result of fmt.Stringer
.
Users could implement the fmt.String* method set by first implementing StringAppend
which would define the result of fmt.Stringer
by simply calling the StringAppend method on a nil byte slice: string(Hexa(1).StringAppend(nil))
.
type Hexa int
func (h Hexa) StringAppend(b []byte) []byte {
return fmt.Appendf(b, "0x%x", h)
}
Metadata
Metadata
Assignees
Labels
Type
Projects
Status