我正在阅读以下文章: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);
在此示例中的语法是什么?
将lt
,LeaveType
指针强制转换为LT
指针。
LT
刚好由type LT LeaveType;
定义为等同于LeaveType
。
这样做是出于评论中解释的原因。
// Define a secondary type to avoid ending up with a recursive call to json.Unmarshal
这是有效还是必要,我不知道。