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 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入