Difference and use of *[]int and []*int

Hi, Can anyone explain these pointer types and useful of these types. Thanks,

2 Likes

While these look similar, these two are actually fairly different and each have unique uses.

The first, *[]int, is a pointer to a slice. I’m not sure how much you know about slices, but Arrays, slices (and strings): The mechanics of 'append' - The Go Programming Language is a great read to get familiar with them. Most notably:

…the contents of a slice argument can be modified by a function, but its header cannot. The length stored in the slice variable is not modified by the call to the function, since the function is passed a copy of the slice header, not the original. Thus if we want to write a function that modifies the header, we must return it as a result parameter, just as we have done here.

What this means is that a slice - eg []int - can have its underlying integer array modified when it is passed into functions, but the headers (how much capacity the slice has, the length of the slice, etc) cannot be.

I’ve actually written about this specific detail a bit more here - Why are slices sometimes altered when passed by value in Go? - Calhoun.io

The TL;DR of when *[]int might be useful is roughly the same as any other type - when you want to pass that slice into a function and allow its data to be modified. This example might help illustrate the difference - Go Playground - The Go Programming Language

[]*int is a slice of integer pointers. That is, while []int is a slice where each element in the slice is an int, []*int is a slice where each element in the slice is a *int (an integer pointer).

Go Playground - The Go Programming Language shows an example of this, and if that were a []int slice those nil entries wouldn’t be value.

Honestly this isn’t something most people tend to use or need very often, so I wouldn’t think on it too much. Chances are if you do end up needing it you will understand their uses more at that point :slight_smile:

8 Likes

@joncalhoun Thanks a lot.

1 Like

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