"gorm目标不支持,应该使用切片或结构"

作者:佚名

时间:2024-03-27

来源:stackoverflow

浏览:129

当我使用这种方式时,没有错误varresultmodel.captchafmt.printf("type:%t",result)iferr:=db.model(&model.captcha{}).where("id=?",randnum).find(&result).error;err!=nil{returnnil,err}但是如果我使用下面的方式,就会出现错误varresult*model.Captchafmt.Printf("Type:%T

当使用 `if err := db.model(&model.captcha{}).where("id = ?", randnum).find(&result).error; err != nil` 时,`result` 的类型为 `model.captcha`,而使用 `if err := DB.Model(&model.Captcha{}).Where("id = ?", randNum).Find(result).Error; err != nil` 时,`result` 的类型为 `*model.Captcha`,这会导致错误。解决办法是将 `result` 定义为 `&models.Captcha{}`,以便使用 `.Find(result)` 而无需使用 `&`。

问题内容

当我使用这种方式时,没有错误

var result model.captcha
fmt.printf("type: %t", result)
if err := db.model(&model.captcha{}).where("id = ?", randnum).find(&result).error; err != nil{
    return nil, err
}

但是如果我使用下面的方式,就会出现错误

var result *model.Captcha
fmt.Printf("Type: %T", result)
if err := DB.Model(&model.Captcha{}).Where("id = ?", randNum).Find(result).Error; err != nil{
    return nil, err
}

result 第一种方式类型为 model.captcha,则 find(&result) 中的 &result 类型为 *model.captcha,第二种方式 result 类型为 *model.captchazqben dczqb,但是第二种方式有错误?

谁能告诉我为什么,谢谢!


解决方案


您应该将 result 定义为 result := &models.Captcha{},这样您就可以使用 .Find(result) 而无需使用 &。

请查看 this go tour link 以更好地理解指针。

当你声明 var result *models.Captcha 时,编译器会创建一个 nil 指针,但是使用 & 可以生成一个指向底层 models.Captcha 的指针,然后 gorm 可以使用这个句柄将 SQL 数据绑定到结构体。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《"gorm目标不支持,应该使用切片或结构"》文章吧,也可关注golang学习网公众号了解相关技术文章。

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
返回顶部