登录
首页 >  Golang >  Go问答

go-automapper 支持映射 time.Time 字段

来源:stackoverflow

时间:2024-02-21 14:51:24 196浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《go-automapper 支持映射 time.Time 字段》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在使用 go-automapper 将值从数据库字段复制到正文发布请求。两个实例的类型相同:

type messagedto struct {
    creationdate time.time          `bson:"creationdate" json:"creationdate,omitempty"`
}

在某个时刻,我尝试从一个实例复制到另一个实例:

func entityToDTO(entity models.MessageDTO) models.MessageDTO{
    dto := &models.MessageDTO{}
    automapper.Map(entity, dto)
    return *dto
}

但它在 time.time 值中失败:

错误映射字段:creationdate。目标类型: models.messagedto 。 源类型:models.messagedto。错误:映射字段错误:墙。 目标类型:时间.时间。源类型:时间.时间。错误:反映: reflect.value.set 使用通过未导出字段获得的值

有办法让它发挥作用吗?


正确答案


错误消息中提到了失败原因:

参考time.time源码:

type Time struct {
    // wall and ext encode the wall time seconds, wall time nanoseconds,
    // ...
    wall uint64
    ext  int64

    // loc specifies the Location that should be used to
    // ...
    loc *Location
}

go-automapper 的文档指出:

所以我认为没有直接的方法可以得到它。也许您可以考虑复制 string 或其他可由 go-automapper 处理的类型中的时间数据,然后使用 (t *time) unmarshalbinary (t *time) unmarshaltext 等接口转换为 zqbc zqbtime.time.

以上就是《go-automapper 支持映射 time.Time 字段》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>