设为首页 加入收藏

TOP

Golang error : "scannable dest type ptr with >1 columns (3) in result"
2023-07-23 13:31:28 】 浏览:26
Tags:Golang error " scannable dest type ptr with > columns result"

项目中的dao层,我们用来查询数据库,获取想要数据。有时我们会需要查询数据给结构体赋值,并返回一个结构体指针,如下

// 结构体字段已与数据库对应
func GetCommunity(id int) (community *model.CommunityDetail, err error) {
	sql := `select community_id, community_name, introduction from community where community_id = ?`
	err = db.Get(&community, sql, id)
	if err != nil {
		return
	}
	return
}

这样的代码看似没有问题,但其实并不正确,运行结果如下

 

如果把&取地址符直接删除,那会直接变成空指针异常。

解决方法

出现上面的问题是因为在函数返回值处,我们只是声明了一个指针model.CommunityDetail类型的指针community,要使用这个指针给结构体赋值之前我们需要先对其进行初始化

func GetCommunity(id int) (community *model.CommunityDetail, err error) {
	sql := `select community_id, community_name, introduction from community where community_id = ?`
	// 初始化
	community = new(model.CommunityDetail)
	err = db.Get(community, sql, id)
	if err != nil {
		return
	}
	return
}

这样我们就可以获取到正确结果了

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇golang编译tag学习 下一篇Gorm 实现无限树形菜单

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目