Home > Net >  Is a type that extends a Map still passed by reference in Go?
Is a type that extends a Map still passed by reference in Go?

Time:08-13

If you have a type in Go, that extends a Map, is this new type still "passed by reference" (or respectively passed as a pointer value)? Or is it copied when used as a function parameter?

Example:

type myMapType map[string][]int

func doSomething(m myMapType) myMapType{

// do something
return m
}

I want to prevent unnecessary copying of data. So do I need a pointer for the above example, or not?

Thanks in advance!

CodePudding user response:

When you declare

type myMapType map[string][]int

You now have a type called myMapType, whose behaviour is the same as map[string][]int.

It's the same as if every instance of myMapType was an instance of map[string][]int, with the only difference being that their types are not considered "the same" in cases where that matters (assignment, type switch, type assertion, etc.).

In other words, myMapType and map[string][]int are equi-valent but not identic-al.

  •  Tags:  
  • go
  • Related