📜 ⬆️ ⬇️

Casting an arbitrary slice to the interface slice

Hello. Anyone who is familiar with Go had a question, but what hell can I not do here and so:


var a = []int{1,2,3} b = []interface(a) 

Why do you have to write like this:


 b := make([]interface{}, len(a)) for i:=0; i<len(a); i++ { b[i] = a[i] } 

But, it is possible and on another ....


I decided to warm up a bit and find a way to make it faster and more convenient. Happened.


Details here .


In short, thanks to the unsafe package, we managed to replace the creation of interface slice and data copying, the creation of interface slice with len and cap of the original slice, and the copying of pointers. Due to the interface implementation features, the free (but not full) COW (copy-on-write) mechanism turned out to be loaded: until you change the data in the final slice, the data in the original and the resulting slice are in the same place, but when the elements of the resulting one change Slice this element will no longer point to the original. In the reverse order, unfortunately, this does not work.


A little bit about performance:


The effectiveness of the solution depends on the size of the slice elements and the length of the slice, the longer the slice and the "weight" of the element - the more effective


https://gist.github.com/t0pep0/af41fba259eb4d3d00d2e7efa0e4093a


')

Source: https://habr.com/ru/post/327110/


All Articles