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

Dor*_*har 1 struct type-conversion go

我有一个struct由自定义定义组成的,time.Time因为它具有自定义MarshalJSON()界面,遵循此答案的建议:

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

我定义了一个MyStruct类型ThisDateThatDate类型的字段*MyTime

type MyStruct struct {
    ThisDate *MyTime `json:"thisdate,omitempty"`
    ThatDate *MyTime `json:"thatdate,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

据我了解,我需要使用*MyTime而不是MyTime这样,当我按照此答案的建议使用这种类型的变量omitempty时,标签才会起作用。MarshalJSON

我使用的库有一个函数,它返回struct带有一些类型字段的a *time.Time

someVar := Lib.GetVar()
Run Code Online (Sandbox Code Playgroud)

我尝试定义一个MyStruct这样的类型变量:

myVar := &MyStruct{
    ThisDate: someVar.ThisDate
    ThatDate: someVar.ThatDate
}
Run Code Online (Sandbox Code Playgroud)

当然,它给了我一个编译错误:

cannot use someVar.ThisDate (variable of type *time.Time) as *MyTime value in struct literal ...
Run Code Online (Sandbox Code Playgroud)

我尝试someVar.ThisDate使用*/&和不使用这些进行打字,但没有运气。我认为以下方法会起作用:

myVar := &MyStruct{
    ThisDate: *MyTime(*someVar.ThisDate)
    ThatDate: *MyTime(*someVar.ThatDate)
}
Run Code Online (Sandbox Code Playgroud)

但它给了我一个不同的编译错误:

invalid operation: cannot indirect MyTime(*someVar.ThisDate) (value of type MyTime) ...
Run Code Online (Sandbox Code Playgroud)

看来我可能缺乏对 Go 中的指针和取消引用的基本理解。尽管如此,我想避免为我的问题找到特定的解决方案,这归结为需要产生omitempty效果和自定义的组合MarshalJSON

Dor*_*har 5

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

*Point(p)        // same as *(Point(p))
(*Point)(p)      // p is converted to *Point
Run Code Online (Sandbox Code Playgroud)

因此,既然*Point需要,*T(v)就应该使用。