Go — pointer parameters, assignment vs dereference

Dig101: dig more, simplified more and know more

A small but common question: how can a function change a pointer (parameter or receiver) so the effect is visible outside the function?

Straight to code — does this work?

1
2
3
4
5
6
7
8
9
type ArgType struct {
A string
b int
}

func modifyPointerArg1(arg *ArgType) {
arg = &ArgType{"arg1", 1}
fmt.Println("inside modifyPointerArg1:", arg)
}

No.

Reason in the next section. What about this?

1
2
3
4
func modifyPointerArg2(arg *ArgType) {
*arg = ArgType{"arg2", 2}
fmt.Println("inside modifyPointerArg2:", arg)
}

Yes.

The difference is easy to miss at first glance.

The first version replaces the pointer variable itself. Inside modifyPointerArg1 that assignment is real, but when the function returns the caller’s pointer still aims at the original object — Go passes arguments by value, including pointer values.

modifyPointerArg2 dereferences the pointer and overwrites what it points at.


There are more ways to do the same thing:

1
2
3
4
5
6
7
func modifyPointerArg3(arg *ArgType) {
val := reflect.ValueOf(arg)
val.Elem().FieldByName("A").SetString("arg3")
fmt.Println("inside modifyPointerArg3:", arg)
// val.Elem().FieldByName("b").SetInt(3)
// panic: reflect: reflect.flag.mustBeAssignable using value obtained using unexported field
}

Reflection’s Elem() pulls out the value behind val:

  • For an empty interface, it returns the value stored inside (that inner value may itself be a pointer).
  • For a pointer, it returns the pointed-to value.

The reflect.Value layout is roughly:

1
2
3
4
5
6
7
8
type Value struct {
// type
typ *rtype
// pointer to data
ptr unsafe.Pointer
// flags
flag
}

Field setters ultimately mutate through that pointer, e.g.:

1
2
3
4
5
6
func (v Value) SetString(x string) {
v.mustBeAssignable()
v.mustBe(String)
// write through v.ptr
*(*string)(v.ptr) = x
}

Tip: unexported fields (lowercase names) cannot be updated this way — you’ll get a panic.

Another option:

1
2
3
4
func modifyPointerArg4(arg *ArgType) {
jsonStr := `{"A":"arg4","b":4}`
json.Unmarshal([]byte(jsonStr), arg)
}

json.Unmarshal also ends up writing through the pointer via reflection.

The same ideas apply if you switch from pointer parameters to pointer receivers, for example:

1
2
3
4
func (arg *ArgType) modifyPointerReceiver4() {
jsonStr := `{"A":"arg4","b":4}`
json.Unmarshal([]byte(jsonStr), arg)
}

Worth trying the other helpers yourself with receivers.

Why bother? One typical use is tests: mock implementations can mutate parameters or receivers to drop real dependencies and keep unit tests focused.

Questions? Leave a comment below or email: newbvirgil@gmail.com