登录
首页 >  Golang >  Go问答

这个函数返回空值

来源:stackoverflow

时间:2024-02-11 13:36:20 235浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《这个函数返回空值》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我是初学者,我编写了一个函数来检查请求中是否 pagination.main == true ,然后该函数返回 prod ,否则返回 prod_2 。默认参数是 main == true ,但如果我将其更改为 false 我得到 "data": null

我的功能:

func getalliproducts(q *models.products, g *models.products_2, pagination *models.params) (*[]models.products, *[]models.products_2) {
    var prod []models.products
    var prod_2 []models.products_2
    offset := (pagination.page - 1) * pagination.limit
    if pagination.main {
        if pagination.cat_id == nil {
            config.db.model(&models.products{}).where(q).limit(pagination.limit).offset(offset).find(&prod)
        } else {
            config.db.model(&models.products{}).where(q).where("cat_id in (?)", pagination.cat_id).limit(pagination.limit).offset(offset).find(&prod)
        }
        return &prod, nil
    } else {
        if pagination.cat_id == nil {
            config.db.model(&models.products_2{}).where(g).limit(pagination.limit).offset(offset).find(&prod_2)
        } else {
            config.db.model(&models.products_2{}).where(g).where("cat_id in (?)", pagination.cat_id).limit(pagination.limit).offset(offset).find(&prod_2)
        }
        return nil, &prod_2
    }
}
func GetAllProducts_by_multi_params(c *gin.Context) {
    pagination := GenerateMultiParams(c)
    var prod models.Products
    var prod_2 models.Products_2
    ProdLists, _ := GetAllIproducts(&prod, &prod_2, &pagination)
    c.JSON(http.StatusOK, gin.H{
        "data": ProdLists,
    })
}

正确答案


第二个返回值由下划线_保持

prodlists, _ := getalliproducts(&prod, &prod_2, &pagination)

您可以将其更改为 prod2lists 并检查 nil,例如:

ProdLists, Prod2Lists := GetAllIproducts(&prod, &prod_2, &pagination)
If ProdLists != nil {
    c.JSON(http.StatusOK, gin.H{
        "data": ProdLists,
    })
} else {
    c.JSON(http.StatusOK, gin.H{
        "data": Prod2Lists,
})}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>