当使用 `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 定义为 请查看 this go tour link 以更好地理解指针。 当你声明 文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《"gorm目标不支持,应该使用切片或结构"》文章吧,也可关注golang学习网公众号了解相关技术文章。 本文内容来源于互联网,如有侵权请联系删除。result 第一种方式类型为 model.captcha,则 find(&result) 中的 &result 类型为 *model.captcha,第二种方式 result 类型为 *model.captchazqben dczqb,但是第二种方式有错误? p>
解决方案
result := &models.Captcha{},这样您就可以使用 .Find(result) 而无需使用 &。var result *models.Captcha 时,编译器会创建一个 nil 指针,但是使用 & 可以生成一个指向底层 models.Captcha 的指针,然后 gorm 可以使用这个句柄将 SQL 数据绑定到结构体。 p>
