How to Map a []Struct to a []interface in Go 🐹

Carlos García Rosales
1 min readNov 5, 2021

--

Versión en Español

In my time programming with go a recurrent problem it’s try to make methods can work with different data type parameters for example what happen when you have a method for insert multiple documents in MongoDB but it’s the same action for different data types. The logic way to solve this problem is use a Interface array as in the next example.

But when you try to send data to this method for example a array of struct you got an error of incompatible types.

So what it’s the solution…

For make this method work and the InsertMany method also too, in my case I have different methods that return me a array of different types of structs in the same method I return that array I map the array to a []interface.

Conclusion

With Go we can solve problems and cases when we need to use a “dynamic type” even if its a strong typed language. I hope help someone with this short format solving little problems you have in your work day.

--

--

Carlos García Rosales

I am Software Developer working in @bayonet.io using the amazing programming language Go! I hope help you with my articles. follow me in my social medias!