Golang中的类型转换

问题描述 投票:0回答:1

我正在阅读以下文章:https://www.ribice.ba/golang-enums/

其中一个代码示例中定义了一个函数:

func (lt *LeaveType) UnmarshalJSON(b []byte) error {
    // Define a secondary type to avoid ending up with a recursive call to json.Unmarshal
    type LT LeaveType;
    var r *LT = (*LT)(lt);
    err := json.Unmarshal(b, &r)
    if err != nil{
        panic(err)
    }
    switch *lt {
    case AnnualLeave, Sick, BankHoliday, Other:
        return nil
    }
    return errors.New("Inalid leave type")
}

var r *LT = (*LT)(lt);在此示例中的语法是什么?

go syntax
1个回答
0
投票

ltLeaveType指针强制转换为LT指针。

LT刚好由type LT LeaveType;定义为等同于LeaveType

这样做是出于评论中解释的原因。

// Define a secondary type to avoid ending up with a recursive call to json.Unmarshal

这是有效还是必要,我不知道。

© www.soinside.com 2019 - 2024. All rights reserved.