How to set value array of struct with pointer in Go

Issue

I have an array of Struct that contains a pointer, i want to set this with some data but when it exit the for loop the value will return nil

heres example :
https://go.dev/play/p/iCiHsVfJkMx

Is there any way to return with complete data, I mean with value on it

Solution

You are ranging over t which is of type []Data. Data is not a pointer type, so v will be set to a copy of t[0], then t[1], etc.

You need to access the struct via array index such that there is an intact chain of references.

https://go.dev/play/p/BqgavPfx16V

Answered By – Zyl

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.