項目中的dao層,我們用來查詢資料庫,獲取想要數據。有時我們會需要查詢數據給結構體賦值,並返回一個結構體指針,如下 // 結構體欄位已與資料庫對應 func GetCommunity(id int) (community *model.CommunityDetail, err error) { sq ...
項目中的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
}
這樣我們就可以獲取到正確結果了