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

我有一个由struct自定义界面组成的自定义界面,time.TimeMarshalJSON()


type MyTime time.Time

func (s myTime) MarshalJSON() ([]byte, error) {

    t := time.Time(s)

    return []byte(t.Format(`"20060102T150405Z"`)), nil

}

我定义了一个MyStruct类型ThisDate和ThatDate类型的字段*MyTime:


type MyStruct struct {

    ThisDate *MyTime `json:"thisdate,omitempty"`

    ThatDate *MyTime `json:"thatdate,omitempty"`

}

据我所知,我需要使用*MyTimeand notMyTime所以当我按照这个答案的建议使用这种类型的变量omitempty时,标签会产生影响。MarshalJSON


我使用一个库,该库具有一个函数,该函数返回struct带有某些类型字段的a *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 中的指针和取消引用缺乏基本的了解。尽管如此,我还是想避免为我的问题找到具体的解决方案,这归结为需要 make have omitemptyan effect 和 custom 的结合MarshalJSON。




慕尼黑8549860
浏览 81回答 1
1回答

慕莱坞森

问题是语法不明确*T(v)或您在那里尝试过的任何其他内容。Golang的规范给出了类型转换的有用示例,引用如下:*Point(p)        // same as  *(Point(p))(*Point)(p)      // p is converted to *Point所以,既然*Point需要,*T(v)就应该使用。
打开App,查看更多内容
随时随地看视频慕课网APP