go - 访问类型声明父方法

标签 go

我正在解码来自 JSON API 的 GET 请求。其中一些字段是 Unix 时间戳(以毫秒为单位)。对于这些字段,我编写了一个处理解码的方法。为此,我需要创建一个新的本地类型 Datetime .

type Datetime time.Time

type Response struct {
  Status    string   `json:"status"`
  CreatedAt Datetime `json:"created_at"`
}


// Handles unmarshalling of Time from the API
func (dt *Datetime) UnmarshalJSON(b []byte) error {
    var unixTimeMs int64
    if err := json.Unmarshal(b, &unixTimeMs); err != nil {
        return err
    }
    *dt = Datetime(time.Unix(0, unixTimeMs*1000000))
    return nil
}

现在我有了这个新的 Response 对象,我想调用 time.Time日期时间的方法。我尝试过转换对象(即 response.CreatedAt.(time.Time)),但这会导致 panic 。

如何调用 time.Time#string 之类的方法在 Datetime ?

最佳答案

Convert日期时间为 time.Time调用Time方法。例子:

fmt.Println(time.Time(dt).String())

另一种方法是使用带有嵌入时间字段的结构:
type Datetime struct {
     time.Time
}

全部 time.Time方法升级为 Datetime类型。修改UnmarshalJSON方法设置dt.Time而不是 *dt .

关于go - 访问类型声明父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61718253/

相关文章:

go - 如何在 Go 中存储 ECDSA 私钥

arrays - 从 slice 中删除特定元素

google-app-engine - AppEngine 日志不接受上下文

windows - 如何使用Go创建的exe创建Windows服务?

go - 创建一个未声明属性的结构

string - 不可变字符串和指针地址

reflection - 戈朗 : Function to determine the arity of functions?

go - golang 中的空函数

go - 初始化与赋值

Golang 短变量声明显示错误未解决