Are Go variables passed as values always copied?

When I pass a variable by value in Go, am I always making a copy of the variable in memory, even if the function receiving this variable only reads (doesn’t mutate) the value? This is more a question about the compiled output than the language itself.

Does it make a difference if it’s a struct vs a string?

From what I’ve read, I get the impression Go always makes a copy of a variable passed by value. Say Go decided to implement a sort of copy-on-write optimisation for function parameters - would this cause any problems?

Take a look at the official FAQ, especially the section about Pointers and Allocation.

When are function parameters passed by value?

As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter. For instance, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to. (See a later section for a discussion of how this affects method receivers.)

Map and slice values behave like pointers: they are descriptors that contain pointers to the underlying map or slice data. Copying a map or slice value doesn’t copy the data it points to. Copying an interface value makes a copy of the thing stored in the interface value. If the interface value holds a struct, copying the interface value makes a copy of the struct. If the interface value holds a pointer, copying the interface value makes a copy of the pointer, but again not the data it points to.

Note that this discussion is about the semantics of the operations. Actual implementations may apply optimizations to avoid copying as long as the optimizations do not change the semantics.

1 Like

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