A
A
Ao2018-11-27 13:16:56
go
Ao, 2018-11-27 13:16:56

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",
  }
  
}

Doesn't work without pointer
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

1 answer(s)
A
Alexander Pavlyuk, 2018-11-27
@darknefrit

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 question

Ask a Question

731 491 924 answers to any question