I have defined a custom (alias) type type Dict map[interface{}]interface{}
with a couple of receiver methods getValue(key interface{}) (interface{}, bool)
and getValue(key interface{}) (interface{}, bool)
.
I'm suspecting that these methods are called by value, i.e. the Dict
is copied by value to the function as the receiver d
.
If I change the receiver to (d *Dict)
, then I need to index using (*d)[key]
, which is very cumbersome.
How can I check whether Dict
is copied by value and change it to copy by reference for efficiency?
package main
import (
"fmt"
)
type Dict map[interface{}]interface{}
func (d Dict) getValue(key interface{}) (interface{}, bool) {
value, found := d[key]
return value, found
}
func (d Dict) setValue(key, value interface{}) {
d[key] = value
}
func main() {
dict := Dict{"foo": "bar", 1: []int{1, 2, 3}}
value, found := dict.getValue(1)
if found {
fmt.Println("value:", value)
}
}
CodePudding user response:
everything in Go is pass by value.
CodePudding user response:
A map is essentially a struct that has a pointer to where the values are stored.
In a way what you are doing is already implicitly passing a reference of the map down to your methods.
So, no need to do anything else. It's fine as it is.