通过自定义类型使用时日期格式发生变化

我对 golang 很陌生,但仍在为很多事情而苦苦挣扎。


当实现像这样的自定义类型时type Date time.Time,定义一种方法来编组/解组"2006-01-02"格式的日期(来自 JSON 文件和 POST API 请求),日期存储在结构中的最终方式是:


{wall:0 ext:63776764800 loc:<nil>}

有人可以帮助我理解为什么这种格式(而不是常规格式time.Time)因为自定义类型Date是大写的,因此被导出了吗?


这是一个实现(链接到代码下方的游乐场):


package main


import (

    "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.Time


func (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


感谢您的帮助和理解。


DIEA
浏览 64回答 1
1回答

慕勒3428872

该类型Date是不同于 的新命名类型time.Time,并且没有为 定义的方法time.Time。marshal/unmarshal 方法工作得很好,但fmt.Print函数族使用Stringer接口(如果存在)。因此,如果您声明:func (d Date) String() string {&nbsp; &nbsp; x, _ := d.MarshalJSON()&nbsp; &nbsp; return string(x)}它将正确打印。
打开App,查看更多内容
随时随地看视频慕课网APP