我對 golang 很陌生,但仍在為很多事情而苦苦掙扎。當(dāng)實現(xiàn)像這樣的自定義類型時type Date time.Time,定義一種方法來編組/解組"2006-01-02"格式的日期(來自 JSON 文件和 POST API 請求),日期存儲在結(jié)構(gòu)中的最終方式是:{wall:0 ext:63776764800 loc:<nil>}有人可以幫助我理解為什么這種格式(而不是常規(guī)格式time.Time)因為自定義類型Date是大寫的,因此被導(dǎo)出了嗎?這是一個實現(xiàn)(鏈接到代碼下方的游樂場):package mainimport ( "encoding/json" "fmt" "log" "time")const sample = `{ "ID": "1", "ticker": "S30J2", "issueDate": "2022-01-31", "maturity": "2023-06-30", "coupon": 0, "cashFlow": [ { "date": "2022-06-30", "rate": 0, "amortization": 1, "residual": 0, "amount": 50}, { "date": "2023-06-30", "rate": 0, "amortization": 1, "residual": 0, "amount": 50} ]}`type Date time.Timefunc (d Date) MarshalJSON() ([]byte, error) { return []byte(time.Time(d).Format("2006-1-2")), nil}func (d *Date) UnmarshalJSON(b []byte) error { // Disregard leading and trailing " t, err := time.Parse("2006-1-2", string(b[1:len(b)-2])) if err != nil { return err } *d = Date(t) return nil}type Flujo struct { Date Date Rate float64 Amort float64 Residual float64 Amount float64}type Bond struct { ID string Ticker string IssueDate Date Maturity Date Coupon float64 Cashflow []Flujo}func main() { var b Bond if err := json.Unmarshal([]byte(sample), &b); err != nil { log.Fatalf("%s", err) } fmt.Printf("%+v\n", b.IssueDate) // I need to wrap it via Format. fmt.Println("Fecha: ", time.Time(b.IssueDate).Format("2006-01-02"))}這里的工作示例:https ://go.dev/play/p/YddzXA9PQdP感謝您的幫助和理解。
1 回答

慕勒3428872
TA貢獻(xiàn)1848條經(jīng)驗 獲得超6個贊
該類型Date是不同于 的新命名類型time.Time,并且沒有為 定義的方法time.Time。marshal/unmarshal 方法工作得很好,但fmt.Print函數(shù)族使用Stringer接口(如果存在)。因此,如果您聲明:
func (d Date) String() string {
x, _ := d.MarshalJSON()
return string(x)
}
它將正確打印。
- 1 回答
- 0 關(guān)注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消