登录
首页 >  Golang >  Go问答

两个结构体指针之间的类型转换

来源:stackoverflow

时间:2024-04-07 18:06:35 292浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《两个结构体指针之间的类型转换》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有一个 struct,它由自定义 time.time 组成,其定义是为了具有自定义 marshaljson() 接口,遵循此答案的建议:

type mytime time.time
func (s mytime) marshaljson() ([]byte, error) {
    t := time.time(s)
    return []byte(t.format(`"20060102t150405z"`)), nil
}

我使用 thisdatethatdate 类型的 *mytime 字段定义 mystruct 类型:

type mystruct struct {
    thisdate *mytime `json:"thisdate,omitempty"`
    thatdate *mytime `json:"thatdate,omitempty"`
}

据我了解,我需要使用 *mytime 而不是 mytime,因此当我按照此答案的建议将 marshaljson 为这种类型的变量时,omitempty 标记将产生效果。

我使用的库有一个函数,该函数返回一个 struct ,其中包含一些类型为 *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 中的指针和取消引用缺乏基本的了解。尽管如此,我还是想避免为我的问题找到特定的解决方案,该解决方案归结为使 omity 发挥作用的需要与自定义 marshaljson 的组合。


解决方案


问题是 *t(v) 或您在那里尝试的任何其他内容的语法不明确。 Golang's spec 给出了类型转换的有用示例,如下所示:

*Point(p)        // same as *(Point(p))
(*Point)(p)      // p is converted to *Point

因此,由于需要 *point,因此应使用 *t(v)

终于介绍完啦!小伙伴们,这篇关于《两个结构体指针之间的类型转换》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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