2

In encoding/json the un-exported reflectValue function passes on all its arguments to another function.

func(e *encodeState) reflectValue(v reflect.Value, opts encOpts)       
{           
    valueEncoder(v)(e, v, opts)
}

The call to valueEncoder can be made from wherever reflectValue is called. What's the motivation for this additional function ?

Sridhar
  • 2,416
  • 1
  • 26
  • 35

2 Answers2

2

The method can be replaced by direct calls to valueEncoder(v)(e, v, opts). The method is not needed to satisfy an interface, nor is it accessed through reflection.

The method was much longer back in 2011. The current method may be there because of the past history. It's also possible that the author thought that code readability is improved by encapsulating valueEncoder(v)(e, v, opts) in a method.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
1

I don't know the motivation of the author of this code. But I suppose that e.reflectValue() is a helper function which makes this code more precies and readable.

When I look at the definition of this fucntion:

func (e *encodeState) reflectValue(v reflect.Value, opts encOpts)

It's pretty clear to me that reflectValue somehow changes encodeState based on reflect value and some encoding options.

When I look at this defintion:

func valueEncoder(v reflect.Value) encoderFunc

I have no idea about what's going on, all I see is a higher-order function.

Function calls are expensive in golang, but encoding/json package is not expected to be very fast.

n-canter
  • 268
  • 1
  • 11