Answer the question
In order to leave comments, you need to log in
Why does assigning a value to a nested structure work with a pointer, but not without a pointer?
Please tell me why assigning values to a nested structure with a pointer works
type TestStruct struct {
Id int
Data map[int]interface{}
}
func main() {
testing := map[int]*TestStruct{}
testing[0]= &TestStruct{
Id:0,
}
testing[0].Data= map[int]interface{}{
1:"dd",
}
}
type TestStruct struct {
Id int
Data map[int]interface{}
}
func main() {
testing := map[int]TestStruct{}
testing[0]= TestStruct{
Id:0,
}
testing[0].Data= map[int]interface{}{
1:"dd",
}
}
Answer the question
In order to leave comments, you need to log in
Because without a pointer, you always get back a copy of the object. You successfully change the field value of this copy, but after that the copy is removed from memory.
To make it work without a pointer, you need to do this :
type TestStruct struct {
Id int
Data map[int]interface{}
}
func main() {
testing := map[int]TestStruct{}
testing[0] = TestStruct{
Id: 0,
}
objCopy := testing[0]
objCopy.Data = map[int]interface{}{
1: "dd",
}
testing[0] = objCopy
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question