by shikaan · 2y ago · 0 comments
""" You might be thinking that it would be more usual to have an ops.Add(ColorOp{Color: red}) method instead of using op.ColorOp{Color: red}.Add(ops). It’s like this so that the Add method doesn’t have to take an interface-typed argument, which would often require an allocation to call. This is a key aspect of Gio’s “zero allocation” design. """
Why would there be an allocation? Of what? How are we saving it?
When a function takes an interface type as an argument, and you pass a pure struct to it, it creates a wrapper around it (this is the allocation referred to in your quote) which is simply a pair of pointers, one being a type/vtable pointer and the other being a pointer to the struct's data.
Doing it this way allows code to do run-time type inference as well as allow interface extension implicitly (that is, implementing an interface is done by implementing its methods, and you don't have to explicitly type it like ByteReader extends Reader"). Since you only pay this cost if you use it, a lot of fast-path code will use structs exclusively if it can.
That's not exactly true. You get one concrete function for all generic pointer types for instance. Generic functions take a hidden paramater called a dictionnary, which is fairly similar to vtable, since it contains type information and pointers for all methods of the generic type that the function calls.
So methods on generic types are still performed through an indirection.
https://github.com/golang/proposal/blob/master/design/generi...
v := interfaceType(concreteTypeValue)
in Go, what you're actually doing on a lower level is: dataPtr := &concreteTypeValue
typePtr := typeData[concreteType]()
v := interfaceData{
data: dataPtr,
typ: typePtr,
}
The first line here is the allocation, since (at least, the way I recall the rule) in Go pointers never point to values on the stack, so concreteTypeValue must be allocated on the heap. The rule about pointers not pointing to the stack is there to make it easier for goroutine stacks to grow dynamically.This is only the case for pointers that the compiler can't prove not to escape:
>In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.
https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename...
(The sibling comment written at the same time has a more detailed explanation of the 'fat' part.)
Others answered your question, but on a different subject: I find that weird to read. To me
op.ColorOp{Color: red}.Add(ops)
reads like “add ops to the result of op.ColorOp{Color: red}. I would name that function AddTo: op.ColorOp{Color: red}.AddTo(ops)
Still unconventional, but at least it messages that the function argument gets modified.