为了与大摇大摆进行交互,我需要制作一个自定义BigInt结构,该结构仅能绕过go's big.Int。
type BigInt struct {
big.Int
}
...
type SpendTx struct {
SenderID string `json:"sender_id,omitempty"`
RecipientID string `json:"recipient_id,omitempty"`
Amount utils.BigInt `json:"amount,omitempty"`
Fee utils.BigInt `json:"fee,omitempty"`
Payload string `json:"payload,omitempty"`
TTL uint64 `json:"ttl,omitempty"`
Nonce uint64 `json:"nonce,omitempty"`
}
func (t SpendTx) JSON() (output []byte, err error) {
return json.Marshal(t)
}
Run Code Online (Sandbox Code Playgroud)
我希望SpendTx.JSON()最终会打来电话big.Int.MarshalJSON(),会回来的0。相反,我得到了以下输出:
{"sender_id":"alice","recipient_id":"bob","amount":{},"fee":{},"payload":"Hello World","ttl":10,"nonce":1}
但是我真正想要的是:
{"sender_id":"alice","recipient_id":"bob","amount":10,"fee":10,"payload":"Hello World","ttl":10,"nonce":1}
而且我必须添加以下代码BigInt来做到这一点:
func (b BigInt) MarshalJSON() ([]byte, error) {
return b.Int.MarshalJSON()
}
Run Code Online (Sandbox Code Playgroud)
但是根据Effective Go的关于嵌入结构的部分,这根本没有必要。为什么big.Int …