Reputation: 7326
I'm only minimally familiar with pointers, but they seem to be a good way to reuse memory, and avoid making extra copies of objects.
Suppose I have a struct
type MyObject struct {
field1 int
field2 string
field3 []string // some long list of long strings
}
I'd like to have two maps
that allow efficient look-up of corresponding objects by their field values
myField1Map := make(map[int]*MyObject)
myField2Map := make(map[string]*MyObject)
OR
myField1Map := make(map[int]MyObject)
myField2Map := make(map[string]MyObject)
Suppose I choose the former
myObj1 := new(MyObject)
myObj1.field1 = 1
myObj1.field2 = "Mufasaaaaa"
myObj1.field3 = []string{// lots and lots of long strings}
myField1Map[myObj1.field1] = myObj1
myField2Map[myObj1.field2] = myObj1
What are my tradeoffs in terms of space efficiency? It seems to me that I am saving space because both maps refer to the same object in memory.
A cool thing was that, I set up a toy problem in Go Playground. I can change a field of a value in one of my maps, and it will show up in the other. This seems like a nice bonus if, suppose, one of these maps was a primary key to this pointer value to the object.
Can someone clarify whether this is the right way to think about pointers and space. Also, is this a common practice? Am I cheating at Go
?
Upvotes: 1
Views: 802
Reputation: 12273
I cannot say if this is a common practice, but it is not cheating at all. Consider that structs are copied in go, therefore you may have a significant loss of space in copying the entire structure.
Note, however, that slices are implicitly pointing to the underlying array. Therefore, if your structure has a slice type for field3
, you would end up copying just a few values, and the actual saving would not be that much - in this case.
Nevertheless, I prefer the solution with pointers. It's conceptually simpler to point to a value if its accessed by two different locations, and in the case you modify one field, you don't have to update the corresponding other as well. (EDIT sorry, I didn't read that you figured this out by yourself :))
Upvotes: 2