Why is thie map creating a new copy?

why are Tel.lookup[“idx”].value and Tel.m.value not the same values… i thought i was saving the reference in the map and when i put the reference out and update it i get a copy of the variable ?

playground link

package main

import (

func main() {
var Tel PkgVar = *Init()
Tel.lookup[“idx”].value = “NewValue”
fmt.Println(Tel.lookup[“idx”].value) <— why are these not the same?
fmt.Println(Tel.m.value) <–

func Init() *PkgVar {
var p PkgVar
p.m = metric{“Original_value”}
p.lookup = map[string]*metric{
“idx”: &p.m,
return &p

type PkgVar struct {
m metric
lookup map[string]*metric

type metric struct {
value string

Please format your code using three backticks like this: ``` your code here ```.
This makes it much easier to read your code in this forum.

By doing this assignment var Tel PkgVar = *Init() you dereference the value and create a copy of that value.
Now Tel.lookup["idx"] still points to &p.m from the Init() function, which is not to same as Tel.m (the local variable).

You can change the assignment to var Tel *PkgVar = Init() so solve that problem.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.