Struct variable not getting increased as expected


(Umang) #1

Hi All,
I have following go code,

package a
type A struct {
  ...
  x int
  ...
}
////
package B
...
x map[string]a.A
...
func GetValByKey(key string) (a.A, bool) {
  val, exist := x[key]
  return val, exist
}
////
package C
func abc(c *gin.Context) {
  ws, err := WsUpgrader.Upgrade(c.Writer, c.Request, nil)
  defer ws.Close() 
  ...
  val, ok := GetValByKey(key)
  val.x++
  ...
  go handleEvents()
  for {
    ...
  }
}

Now when I call the endpoint with same key, value of x is getting increased from 0 in both cases. i.e.
first call,
value of x(before ++) := 0
value of x(after ++) := 1
second call,
value of x(before ++) := 0
value of x(after ++) := 1
But for second call, I want it to be
value of x(before ++) := 1
value of x(after ++) := 2
I am not able to figure out what could be the issue. can you please help?


(Gerard) #2

Isn’t a struct copy by value? So everytime you call GetValByKey(key) it returns a copy of the struct.


(Gerard) #3

Won’t you need to change your map values to pointers to values? Something like below:
package main

package main

import (
	"fmt"
	"os"
)

type a struct {
	x int
}

type mapStrToAPtr map[string]*a

func getPtrValByKey(key string, m mapStrToAPtr) (*a, bool) {
	val, exist := m[key]
	return val, exist
}

func main() {
	m := map[string]*a{
		"G4143":  {4143},
		"Emily":  {1234},
		"Angela": {4321},
	}
	for key, value := range m {
		fmt.Fprintf(os.Stdout, "%s -> %d\n", key, *value)
	}
	if p, ok := getPtrValByKey("G4143", m); ok {
		p.x++
	}
	for key, value := range m {
		fmt.Fprintf(os.Stdout, "%s -> %d\n", key, *value)
	}
}