项目中的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
}

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

Golang error : "scannable dest type ptr with >1 columns (3) in result"

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

解决方法

出现上面的问题是因为在函数返回值处,我们只是声明了一个指针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 error : "scannable dest type ptr with >1 columns (3) in result"

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。