Functional in Golang: immutable and return vs. manipulation references


this question is about the conceptional design of Golang and I did not find much information about this:

In many other especially with a functional painting languages it is more and more en vogue (with good cause) to return results instead of manipulating arguments.

In Golang in contrast one can see often that manipulating references instead of returns are used (e. g. the Scan functions of the database package) but using return values as well (e. g. append).

Are there any conceptional rules when to use the one or to use the other?

Sometimes your hand is forced. For example, the database Scan function can’t return the scanned values because it doesn’t know what type they should be. Hence you need to pass it pointers (Go doesn’t have “references” and the terminology is frowned upon) to the values you want scanned into.

In other cases it’s a matter of performance. for example io.Reader’s Read function takes a byte slice to read into. It could return a new byte slice for you instead, but then it would need to allocate on every call and the slice could not be reused.

When you can efficiently return immutable value types, do so. Most of the time package works like this for example.

For methods it’ll be a question of either necessity or performance. Again the time package showcases one way to do it, where the methods (not counting Unmarshal) don’t modify the receiver. In other cases when you have large structs or need to modify state, the methods need to take a pointer receiver.

All in all, Go takes a more pragmatic than dogmatic approach to this. :slight_smile: You should probably not attempt to follow a functional programming mindset / methodology in Go. It’ll hurt.


Hi Calmh,

thank you for this answer. It is always difficult in unknown languages to find best practises and common usages. So your explanation helps me a lot.


Great answer, thanks @calmh!

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