1 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用reflect內(nèi)置包來(lái)執(zhí)行此操作。這是一個(gè)例子:
main.go
package main
import (
"fmt"
"reflect"
)
type Repo struct {
Key string `json:"key"`
Type string `json:"type"`
PackageType string `json:"packageType"`
}
var someDatas = []Repo{
{
Key: "test",
Type: "test",
PackageType: "test",
},
{
Key: "test1",
Type: "test1",
PackageType: "test1",
},
{
Key: "test",
Type: "LOCAL",
PackageType: "test23",
},
}
func getWantedRepos(conf map[string]interface{}) []Repo {
var returned []Repo
for _, val := range someDatas {
flag := true
for k := range conf {
if !reflect.DeepEqual(reflect.ValueOf(val).FieldByName(k).Interface(), conf[k]) {
flag = false
break
}
}
if flag {
returned = append(returned, val)
}
}
return returned
}
func main() {
var repos []Repo
repos = getWantedRepos(map[string]interface{}{
"Key": "test",
})
fmt.Println("1 ============================")
fmt.Printf("%+v\n", repos)
repos = getWantedRepos(map[string]interface{}{
"Type": "LOCAL",
})
fmt.Println("2 ============================")
fmt.Printf("%+v\n", repos)
repos = getWantedRepos(map[string]interface{}{
"Type": "LOCAL",
"PackageType": "test23",
})
fmt.Println("3 ============================")
fmt.Printf("%+v\n", repos)
repos = getWantedRepos(map[string]interface{}{
"Type": "LOCAL",
"PackageType": "NONE",
})
fmt.Println("4 ============================")
fmt.Printf("%+v\n", repos)
}
Output:
1 ============================
[{Key:test Type:test PackageType:test} {Key:test Type:LOCAL PackageType:test23}]
2 ============================
[{Key:test Type:LOCAL PackageType:test23}]
3 ============================
[{Key:test Type:LOCAL PackageType:test23}]
4 ============================
[]
我使用map[string]interface{}模型過(guò)濾而不是模型過(guò)濾,因?yàn)槿绻褂媚P?,例如帶有string屬性,則默認(rèn)值為string“”。即使你沒(méi)有初始化屬性的值,它也會(huì)有“”作為默認(rèn)值,reflectfor循環(huán)會(huì)掃描并嘗試用空字符串“”匹配模型,所以為了避免這種情況,我使用map[string]interfaceso we更靈活地選擇我們想要的屬性,反之亦然。
我不知道您有什么測(cè)試用例,但是如果您從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù),請(qǐng)嘗試使用WHERE而不是這樣做。
- 1 回答
- 0 關(guān)注
- 114 瀏覽
添加回答
舉報(bào)