doushi9474 2019-05-25 19:21
浏览 141
已采纳

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

I have a struct that consists of a custom time.Time defined for the sake of it having a custom MarshalJSON() interface, following this answer's suggestion:

type MyTime time.Time
func (s myTime) MarshalJSON() ([]byte, error) {
    t := time.Time(s)
    return []byte(t.Format(`"20060102T150405Z"`)), nil
}

I define a MyStruct type with ThisDate and ThatDate fields of type *MyTime:

type MyStruct struct {
    ThisDate *MyTime `json:"thisdate,omitempty"`
    ThatDate *MyTime `json:"thatdate,omitempty"`
}

As far as I understand, I need to use *MyTime and not MyTime so the omitempty tag will have an effect when I'll MarshalJSON a variable of this type, following this answer's suggestion.

I use a library that has a function that returns me a struct with some fields of type *time.Time:

someVar := Lib.GetVar()

I tried to define a variable of type MyStruct like this:

myVar := &MyStruct{
    ThisDate: someVar.ThisDate
    ThatDate: someVar.ThatDate
}

Naturally, it gives me a compilation error:

cannot use someVar.ThisDate (variable of type *time.Time) as *MyTime value in struct literal ...

I tried typecasting someVar.ThisDate with */& and without these without luck. I thought the following would work:

myVar := &MyStruct{
    ThisDate: *MyTime(*someVar.ThisDate)
    ThatDate: *MyTime(*someVar.ThatDate)
}

But it gives me a different compilation error:

invalid operation: cannot indirect MyTime(*someVar.ThisDate) (value of type MyTime) ...

It seems I probably lack basic understanding of pointers and dereferences in Go. Never the less, I would like to avoid finding a specific solution for my issue which comes down to the combination of the need to make omitempty have an effect and a custom MarshalJSON.

  • 写回答

1条回答 默认 最新

  • dongyi1996 2019-05-28 06:43
    关注

    The problem is the ambiguous syntax of *T(v) or whatever else you tried there. The Golang's spec gives useful examples for type conversions as this, quoting:

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

    Therefor, since *Point is needed, *T(v) should be used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?