0

I have a slice of int32 that wants to convert to slice of int in Golang. I can convert it by iterating all values and changing the type then append it to a new int slice but I want to do it more optimized. Is there any way or function to do it?

For example :

var a []int32{1,2,3,4}

How can a convert a type from []int32 to []int?

  • 4
    Using the loop for the iteration is the correct approach, see this [FAQ](https://go.dev/doc/faq#convert_slice_of_interface) and this [FAQ](https://go.dev/doc/faq#convert_slice_with_same_underlying_type). – mkopriva Dec 03 '22 at 10:35
  • 2
    However, keep in mind that with Go1.18 and up, using generics, you can implement this once for any combination of integers. For example: https://go.dev/play/p/FYq6TgWlULK – mkopriva Dec 03 '22 at 10:46

0 Answers0