drghhp8706 2019-04-22 12:55
浏览 16
已采纳

使用接口参数的怪异行为

When i call a function with an interface{} parameters with a *[]interface{}, the behavior is expected, but when I call the function with []interface{}, and then use the parameter with & it doesn't work why ?

func routeWarehouses(engine *gin.Engine) {
    var test []database.Warehouses
    router.GET("/", genericReads(test))
}

func genericReads(i interface{}) func(c *gin.Context) {
    return func(c *gin.Context) {
        // When i call genericReads with `test`
        //println(reflect.TypeOf(i).Kind()) // Slice
        //println(reflect.TypeOf(i).Elem().Kind()) // Struct

        // When i call genericReads `&test`
        //println(reflect.TypeOf(i).Kind()) // Ptr
        //println(reflect.TypeOf(i).Elem().Kind()) // Slice
        //println(reflect.TypeOf(i).Elem().Elem().Kind()) // Struct

        // When I call database.Reads with `i` ( passed as `&test` ), It's works, I get all rows of the Model otherwise
        // When I call database.Reads with `&i` ( passed as `test` ), It doesn't work ( I get `unsupported destination, should be slice or struct` )
        if err := database.Reads(&i, database.Warehouses{}); err != nil {
            utils.R500(c, err.Error())
            return
        }

        c.JSON(http.StatusOK, i)
    }
}
func Reads(i interface{}, column ColumnSpell) error {
    if err := DB.Debug().Find(i).Error; err != nil {
        return errors.New(fmt.Sprintf("Cannot reads %s: %s", column.Plural(), err.Error()))
    }

    return nil
}

PS: Maybe this come directly from Gorm ?

  • 写回答

1条回答 默认 最新

  • donglao7947 2019-04-22 13:16
    关注

    It is because a slice is already a pointer (https://golang.org/ref/spec#Slice_types).

    So to set a pointer to a slice is setting a pointer to a pointer. So just remeber if you are dealing with slices they are pointers to arrays.

    More information how the slices are used as a pointer are here: https://golang.org/doc/effective_go.html#slices

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

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画