Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const reference in C++ and equivalent in Golang

Tags:

go

I came to go from the C++ world and in C++ usually when you care about performance and you don't need you object to be changed, you pass it using constant reference

void func(const std::string& str)

In this case, the string is NOT COPIED and cannot be modified in the function.

I know, that in Go there are two ways to pass object:

  • By value, and then you cannot modify (or actually you can but it makes no sense) it, but it very memory consuming
  • By pointer, this is good from the terms of memory, but you can modify object.

So, what is best approach? Always pass object by pointer even if you don't want to modify it because it is faster? Or there are some compiler optimizations and even if you send it by value sometimes it is sent as reference?

like image 986
Georgy Buranov Avatar asked Apr 11 '16 14:04

Georgy Buranov


1 Answers

There's no direct equivalent in Go.

  1. Pass by pointer if the object is big (~bigger than 32-64bytes) and/or requires changing.
  2. Pass by value if the above rule doesn't apply.
  3. maps/channels/slices are reference-types, they contain inner pointers, so you don't need to pass them by pointer unless you plan on possibly passing a nil or want to append (not modify already contained elements) to a slice.

Example:

func doMap(m *map[string]string) {
    if *m == nil {
        *m = map[string]string{}
    }
    .....
}
like image 53
OneOfOne Avatar answered Sep 19 '22 11:09

OneOfOne