In Donovan and Kernighan's p333 (section 12.3 Display, a recursive value printer), it is mentioned that
Where possible, you should avoid exposing reflection in the API of a package. We'll define an unexported function
display
to do the real work of the recursion, and exportDisplay
, a simple wrapper around it that accepts aninterface{}
parameter.
func Display(name string, x interface{}) {
fmt.Printf("Display %s (%T):\n", name, x)
display(name, reflection.ValueOf(x))
And the display
function prints different contents depending on the Kind
of the input reflection value.
I have two questions
- Why is it better to not expose the reflection in the package API?
- Why is using an unexposed
display
function considered as not exposing reflection in the API? Don't we still callreflection.ValueOf()
inDisplay
?
I guess I don't know the definition of "exposing reflection in the package API". Does it just refer to the function arguments or both arguments and content? If it's the former case, then there is no need to define both display
and Display
. If it's the latter case, why is it better?
Aucun commentaire:
Enregistrer un commentaire