Friday, March 1, 2024
HomeGolangReturning slice of pointers vs pointer to slice - Getting Assist

Returning slice of pointers vs pointer to slice – Getting Assist


I need to return []Class.
However I’m confused which one is healthier choice?

func GetCategories() (*[]Class, error) {}
func GetCategories() ([]*Class, error) {}

Between this which one does go follows?

Is it okay to do one thing like this?
func GetCategories() (*[]*Class, error) {} //haven’t tried this.

There’s not a lot level to returning a pointer to a slice.

So return it.
At all times have a purpose to go pointer. You need to default to not use pointers.

There may be

Would you care to elaborate? I can’t consider any case the place returning a pointer to a slice is a good suggestion. It will allow you to distinguish between p == nil vs. *p == nil, however I’d be concerned with seeing the code that makes use of the consequence. I imaging there can be a greater manner to do this (e.g. return a pointer to a struct with a single slice area, possibly?).

Nevertheless, I do agree with you that it is best to have a purpose to make use of a pointer and should you don’t know should you do or not, then you do not want a pointer.

1 Like

Agreed. I can see passing a pointer to an array, however not a slice as it holds a reference to an underlying array anyway:

Slices maintain references to an underlying array, and should you assign one slice to a different, each seek advice from the identical array. If a perform takes a slice argument, modifications it makes to the weather of the slice shall be seen to the caller, analogous to passing a pointer to the underlying array.

1 Like



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments