Slices preferred to arrays?

Very basic style question for you. In https://tour.golang.org/moretypes/17, line 6 is pow := make([]int, 10). Why not just var pow [10]int? The latter is equivalent for the demo’s purpose, and conceptually simpler. Are slices generally preferred to arrays even when the latter will do? Why? And is there actually runtime overhead to using slices instead of their backing arrays directly, or does the compiler eliminate it?

1 Like

Slices are used almost exclusively in Go code unless you have a very good reason to use an array instead. For more I would start with this article - https://blog.golang.org/go-slices-usage-and-internals

As to a few of your questions:

Why not just var pow [10]int? The latter is equivalent for the demo’s purpose, and conceptually simpler. Are slices generally preferred to arrays even when the latter will do?

You could do this, and in generated code you will often see arrays being used instead of slices, but when people are reading and writing the code slices are often more flexible and easier to use.

And is there actually runtime overhead to using slices instead of their backing arrays directly, or does the compiler eliminate it?

Yes, there is overhead, but 99%+ of the time it is negligible.

There is also a runtime overhead to arrays, as you are copying the entire array in functions calls, loops, etc instead of just the small slice struct. For small arrays this doesn’t matter but for larger ones it becomes significant.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.