0

For example,

func foo() {
    return map[string]interface{}{}
}

func baz(){
    a := foo()
}

every time the baz() was called, was the map also copied? If yes and the map is very complex, would the process take much time to do the copy operation?

Paul Zhang
  • 305
  • 2
  • 7
  • 1
    Yes, the map is copied. No, copying a map is O(1). – Volker May 05 '22 at 08:08
  • If the returned value is a struct, would it be slow? @Volker – Paul Zhang May 05 '22 at 08:18
  • 2
    Everything is passed (and returned) by value, which means a copy is made. Maps are implemented as pointers, so passing (and returning) a map simply passes (and returns) a pointer value under the hood. – icza May 05 '22 at 08:19
  • 2
    @PaulZhang you need to define "slow". – zerkms May 05 '22 at 08:24
  • 2
    It's bad practice to think about "slow" or "fast" _unless_ realistic load tests have identified that this code path is hot and the bottleneck of the application. Sometimes it's sensible to not do things badly but most of the time when people think about "will this be slow" it doesn't matter the slightest as this is not the code part making the application slow. – Volker May 05 '22 at 08:40
  • 1
    In this case, nothing is getting _copied_. Each invocation of `foo` (and, therefore, of`baz`) simply initialises a new map. – jub0bs May 05 '22 at 16:33

1 Answers1

0

In that case a new pointer to a map is created each time the function is executed.

Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn’t point to an initialized map.

See: https://go.dev/blog/maps

Also, go has pointers to decide when to return a copy or not. For example https://go.dev/play/p/Pibhj5onIIL

ryuk
  • 99
  • 1
  • 5