使用接口参数的奇怪行为

问题描述 投票:-4回答:1

当我使用带有interface{}*[]interface{}参数调用函数时,行为是预期的,但是当我用[]interface{}调用函数,然后使用&的参数时它不起作用的原因?

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:也许这直接来自Gorm?

go
1个回答
1
投票

这是因为切片已经是指针(https://golang.org/ref/spec#Slice_types)。

因此,设置指向切片的指针是设置指针的指针。所以,请记住,如果你正在处理切片,他们是指向数组的指针。

有关切片如何用作指针的更多信息,请访问:https://golang.org/doc/effective_go.html#slices

© www.soinside.com 2019 - 2024. All rights reserved.