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

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条)

报告相同问题?

悬赏问题

  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?