douchunji1885 2015-02-24 15:08
浏览 31
已采纳

使用函数通过方法满足接口

I am trying to write a method that will return a function that can satisfy the json.Marshaler interface. My reasoning is to provide different representations of the struct. Perhaps I am approaching this completely wrong.

func (api *Api) SiteList(c *gin.Context) {
    var sites []db.Site
    if err := api.db.Find(&sites).Error; err != nil {
    }
    var payload []json.Marshaler
    for _, site := range sites {
        payload = append(payload, site.ToApi())
    }
    c.JSON(http.StatusOK, payload)
}

The result I get from this function is the correct number of items in the list, but the same value for each:

[
    {
        "key": "NZ7LCA9HQN3", 
        "name": "autumn-waterfall-1573"
    }, 
    {
        "key": "NZ7LCA9HQN3", 
        "name": "autumn-waterfall-1573"
    }, 
    {
        "key": "NZ7LCA9HQN3", 
        "name": "autumn-waterfall-1573"
    }, 
    {
        "key": "NZ7LCA9HQN3", 
        "name": "autumn-waterfall-1573"
    }, 
    {
        "key": "NZ7LCA9HQN3", 
        "name": "autumn-waterfall-1573"
    }
]

Finally, here is the ToApi implementation:

type EncoderFunc func() ([]byte, error)

func (fn EncoderFunc) MarshalJSON() ([]byte, error) {
    return fn()
}

func (site *Site) ToApi() json.Marshaler {
    return EncoderFunc(func() ([]byte, error) {
        var payload public.Site
        payload.Name = site.Name
        payload.Key = site.Key
        data, err := json.Marshal(payload)
        if err != nil {
            return nil, err
        }
        return data, nil
    })
}
  • 写回答

1条回答 默认 最新

  • douweng7308 2015-02-24 15:35
    关注

    This seems like a classic closure gotcha. There is a related FAQ section.

    Basically, site in your for-loop has the same address every time. All your functions are closed over this address. So when you evaluate it after the for-loop, it will repeatedly call MarshalJSON on the value on the same (last) address. You can correct that by creating a new value on every iteration:

    for _, site := range sites {
        site := site // Perfectly legal and idiomatic.
        payload = append(payload, site.ToApi())
    }
    

    Playground: https://play.golang.org/p/eFujC1hEyD

    Another related piece of documentation from Effective Go:

    The bug is that in a Go for loop, the loop variable is reused for each iteration, so the req variable is shared across all goroutines. That's not what we want. (...) Another solution is just to create a new variable with the same name, as in this example:

    for req := range queue {
        req := req // Create new instance of req for the goroutine.
        sem <- 1
        go func() {
            process(req)
            <-sem
        }()
    }
    

    This section is about goroutines, but apparently this also applies to all closures.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角