我有一個由struct自定義界面組成的自定義界面,time.TimeMarshalJSON()type MyTime time.Timefunc (s myTime) MarshalJSON() ([]byte, error) {? ? t := time.Time(s)? ? return []byte(t.Format(`"20060102T150405Z"`)), nil}我定義了一個MyStruct類型ThisDate和ThatDate類型的字段*MyTime:type MyStruct struct {? ? ThisDate *MyTime `json:"thisdate,omitempty"`? ? ThatDate *MyTime `json:"thatdate,omitempty"`}據(jù)我所知,我需要使用*MyTimeand notMyTime所以當我按照這個答案的建議使用這種類型的變量omitempty時,標簽會產生影響。MarshalJSON我使用一個庫,該庫具有一個函數(shù),該函數(shù)返回struct帶有某些類型字段的a *time.Time:someVar := Lib.GetVar()我試圖定義MyStruct這樣一個類型的變量:myVar := &MyStruct{? ? ThisDate: someVar.ThisDate? ? ThatDate: someVar.ThatDate}自然地,它給了我一個編譯錯誤:cannot use someVar.ThisDate (variable of type *time.Time) as *MyTime value in struct literal ...我嘗試someVar.ThisDate使用*/&和不使用這些進行類型轉換,但運氣不佳。我認為以下方法可行:myVar := &MyStruct{? ? ThisDate: *MyTime(*someVar.ThisDate)? ? ThatDate: *MyTime(*someVar.ThatDate)}但它給了我一個不同的編譯錯誤:invalid operation: cannot indirect MyTime(*someVar.ThisDate) (value of type MyTime) ...看來我可能對 Go 中的指針和取消引用缺乏基本的了解。盡管如此,我還是想避免為我的問題找到具體的解決方案,這歸結為需要 make have omitemptyan effect 和 custom 的結合MarshalJSON。
兩個結構指針之間的類型轉換
慕尼黑8549860
2023-06-19 16:56:49