这个函数存在的原因是什么?

huangapple go评论81阅读模式
英文:

What's a reason for this function to exist?

问题

encoding/json中,未导出的reflectValue函数将其所有参数传递给另一个函数。

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

可以从调用reflectValue的任何地方调用valueEncoder函数。这个额外函数的动机是什么?

英文:

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 ?

答案1

得分: 2

该方法可以通过直接调用valueEncoder(v)(e, v, opts)来替代。该方法不需要满足接口的要求,也不通过反射进行访问。

该方法在2011年的时候更长。当前的方法可能是因为过去的历史而存在。也有可能是作者认为通过将valueEncoder(v)(e, v, opts)封装在一个方法中可以提高代码的可读性。

英文:

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.

答案2

得分: 1

我不知道这段代码的作者的动机。但我猜测e.reflectValue()是一个辅助函数,使得这段代码更加精确和可读。

当我看到这个函数的定义时:

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

对我来说很清楚,reflectValue根据反射值和一些编码选项来改变encodeState。

当我看到这个定义时:

func valueEncoder(v reflect.Value) encoderFunc

我不知道发生了什么,我只看到一个高阶函数。

在golang中,函数调用是昂贵的,但是encoding/json包不被期望非常快。

英文:

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.

huangapple
  • 本文由 发表于 2017年2月5日 04:04:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/42045007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定