【发布时间】:2014-09-05 20:33:20
【问题描述】:
试图检查某个切片中的结构是否包含给定字段的值,所以我写了这个
func main() {
//test
Objs := []Obj{{1,"xxx"},{2,"yyy"},{3,"zzz"}}
res := containsStructFieldValue(Objs,"X",1)
fmt.Println(res)
}
type Obj struct {
X int
Y string
}
func containsStructFieldValue(slice []Obj ,fieldName string,fieldValueToCheck interface {}) bool{
for _,s := range slice{
r := reflect.ValueOf(s)
f := r.FieldByName(fieldName)
if f.IsValid(){
if f.Interface() == fieldValueToCheck{
return true //a field with the given value exists
}
}
}
return false
}
我需要它适用于任何给定的结构类型,但是当我尝试slice []interface 作为参数时,我发现它不可能,关于如何使上述方法适用于任何结构类型的任何想法?
【问题讨论】:
标签: go