dougaicha5258 2019-07-11 19:26
浏览 1228
已采纳

Golang地址运算符和(* int)(Type)语法

Starting to play around with golang and was looking at a custom json.Unmarshal. In a blog post the had the following:

type FlexInt int

func (fi *FlexInt) UnmarshalJSON(data []byte) error {
    if data[0] != '"' {
        return json.Unmarshal(data, (*int)(fi))
    }
    var s string
    if err := json.Unmarshal(data, &s); err != nil {
        return err
    }
    i, err := strconv.Atoi(s)
    if err != nil {
        return err
    }
    *fi = FlexInt(i)
    return nil
}

And I understand what it is doing - but I dont understand (*int)(fi) part. Looking at the value of the fi pointer it is the same as (*int)(fi) - (*int)(fi) == fi. Yet when I change that line to simply fi it then does an infinite loop

  • 写回答

2条回答 默认 最新

  • donglengli0644 2019-07-11 19:31
    关注

    The expression converts fi to an *int. The result contains the same address, but has a different type.

    If a *FlexInt is passed to json.Unmarshal, then json.Unmarshal will call the *FlexInt.UnmarshalJSON method which calls json.Unmarshal and so on.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?