2 ms·
I won't go into super much detail, but think of generics as functions over types that generate new types based on type inputs (gross oversimplification). Compar
by spoiler 5y ago
I won't go into super much detail, but think of generics as functions over types that generate new types based on type inputs (gross oversimplification). Comparable to functions that take value and return values, also it happens before your program runs (during compilation/build time).
A ring buffer is just a normal buffer, except that when it "runs out" of space instead of overflowing or returning an error, it "loops back" on itself, and starts writing from the start. You can still grow it, if needed.
The nice thing about generics here is that it allows you to have a RingBuffer[string], RingBuffer[int], and RingBuffer[MyType] without having to implement them separately. The compiler will even take care of memory sizing/layout, and all the other razzledazzle.
As for performance, it's not fully related to generics, but a sibling comment explained the implementation detail and how it affects performance.
- throwaway77384 5y agoThank you for the information. Much appreciated!
- travisby 5y agoIt might also be worth comparing to the stdlib's `container/ring` implementation of a non-generic ring buffer, to see how your code might differ between `RingBuffer[string]` and how the `interface{}` version of container/ring works! https://pkg.go.dev/container/ring#example-Ring.Do https://pkg.go.dev/container/ring#example-Ring.Do The casting back and forth from T and `interface{}` is expensive, boilerplatey/extracode, and panic-prone.
- gavinclarke0 5y agoI implemented it using generics not for performance gains but to avoid type assertions and interfaces which I find are a major source of error and side step many of the benefits of a type safe language. Any performance gains is merely a side affect.