Published on

Passing Structs Around in Go

Authors

Coming from a Java background ,with a sprinkling of C at varsity, having to explicitly worry about whether I am going to pass a struct by value or reference is quite new.

A colleague very well versed in C gave me the following guidelines:

// the following will convert a pointer back to a struct
myStruct = *someStructPointer

// the following will convert a struct to a pointer
aPointerToStruct = &someStruct

And in functions you use them as follows:

// the below struct is pass by reference meaning that any changes you make to fields on it will reflect on the original struct
func someMutatingFunction(structToMod *MyStruct) {
    //...
}

// the below struct is pass by value meaning that changes to it inside the function will not affect the struct that was passed in
func someNoneMutatingFunction(structToRead Mystrut) {
    //...
}

One weirdness is you always pass an interface to a function by value.