mercredi 29 novembre 2023

Design pattern - json.Unmarshal()

Second argument of json.Unmarshal() api allows passing value of receiver type that implements below interface:

type Unmarshaler interface {
    UnmarshalJSON([]byte) error
}

json.Unmarshal() under the hood, uses reflect package, to find and invoke UnmarshalJSON() method of the receiver type(as shown below):

u, ut, pv := indirect(v, isNull)
if u != nil {
    return u.UnmarshalJSON(item)
}

Is there a term(design pattern name) for this approach(to inspect receiver type at runtime and invoke methods of that type)?

Aucun commentaire:

Enregistrer un commentaire