第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有零/空值的指針上的客戶解組器/編組器

具有零/空值的指針上的客戶解組器/編組器

Go
達令說 2023-02-21 15:49:26
Golang - 具有零/空值的指針上的客戶解組器/編組器我正在嘗試實現(xiàn)自定義UnmarshalJSON和MarshalJSON指針類型,但是當(dāng)來自 json 的數(shù)據(jù)null/nil如下例所示時,不會調(diào)用此函數(shù):package mainimport (    "encoding/json"    "fmt")type A struct {    B *B `json:"b,omitempty"`}type B int// Only for displaying value instead of// pointer address when calling `fmt.Println`func (b *B) String() string {    if b == nil {        return "nil"    }    return fmt.Sprintf("%d", *b)}// This function is not triggered when json// data contains null instead of number valuefunc (b *B) UnmarshalJSON(data []byte) error {    fmt.Println("UnmarshalJSON on B called")    var value int    if err := json.Unmarshal(data, &value); err != nil {        return err    }    if value == 7 {        *b = B(3)    }    return nil}// This function is not triggered when `B`// is pointer type and has `nil` valuefunc (b *B) MarshalJSON() ([]byte, error) {    fmt.Println("MarshalJSON on B called")    if b == nil {        return json.Marshal(0)    }    if *b == 3 {        return json.Marshal(7)    }    return json.Marshal(*b)}func main() {    var a A    // this won't call `UnmarshalJSON`    json.Unmarshal([]byte(`{ "b": null }`), &a)    fmt.Printf("a: %+v\n", a)    // this won't call `MarshalJSON`    b, _ := json.Marshal(a)    fmt.Printf("b: %s\n\n", string(b))    // this would call `UnmarshalJSON`    json.Unmarshal([]byte(`{ "b": 7 }`), &a)    fmt.Printf("a: %+v\n", a)    // this would call `MarshalJSON`    b, _ = json.Marshal(a)    fmt.Printf("b: %s\n\n", string(b))}輸出:a: {B:nil}b: {}UnmarshalJSON on B calleda: {B:3}MarshalJSON on B calledb: {"b":7}我的問題是:為什么UnmarshalJSON/MarshalJSON不使用null/nil指針類型的值調(diào)用我們?nèi)绾蜺nmarshalJSON/MarshalJSON每次調(diào)用數(shù)據(jù)null/nil和類型是指針而不是UnmarshalJSON/MarshalJSON在A類型上實現(xiàn)并b從級別修改屬性A
查看完整描述

1 回答

?
夢里花落0921

TA貢獻1772條經(jīng)驗 獲得超6個贊

簡稱

目前,解組/編組 Go 結(jié)構(gòu)將僅發(fā)出非零字段,因為在 Go 中nil pointer是一個零值,在這種情況下不會調(diào)用。UnmarshalJSON/MarshalJSON


另外,似乎有一些相關(guān)的建議

但是,現(xiàn)在沒有辦法解決。


每個代碼 解組器

Unmarshalers 將 UnmarshalJSON([]byte("null")) 實現(xiàn)為空操作

// By convention, to approximate the behavior of Unmarshal itself,

// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.

type Unmarshaler interface {

    UnmarshalJSON([]byte) error

}


查看完整回答
反對 回復(fù) 2023-02-21
  • 1 回答
  • 0 關(guān)注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號