如何在GO中使用过滤器参数过滤结构切片

时间:2021-04-17 21:45:24

标签: go struct

我是 GOlang 的新手,我尝试使用 struct 过滤 GO 中的 struct 切片,其中包含一些用于过滤它的参数。我正在尝试做以下事情,但它对我不起作用。在该代码中,我有过滤器函数,它采用结构的切片,即需要使用 FilterParameter 结构过滤的 GRN。

需要归档的我的结构

type GRN struct {
        DocType          string    `json:"docType"`
        GRNNO            string    `json:"GRNNO"`
        PRID             string    `json:"PRID"`
        PRODUCE          string    `json:"PRODUCE"`
        VARIETY          string    `json:"VARIETY"`
}


manyGRNUsers := []GRN{{"GRNAsset","GRN0000109","PRFAINAPKR0086","Sweetcorn","CP2"},
    {"GRNAsset","GRN0000110","PRFAINAPKR0087","Sweetcorn","CP1",},
    {"GRNAsset","GRN0000112","PRFAINAPKR0087", "Sweetcorn","CP2",},
    {"GRNAsset","GRN0000113","PRFAINAPKR0089","Apple","Gala",}}

将用于过滤器参数的结构。在这里,FilterParameter 中的字段是动态的,如上面的 GRN 结构值。它可以超过两个字段但小于或等于 GRN 结构字段

  type FilterParameter struct {
        PRODUCE            string    `json:"PRODUCE"`
        VARIETY          string    `json:"VARIETY"`
    
    }

manyFilterParameter := []FilterParameter{{"Sweetcorn","CP2" }

我尝试了下面的函数,但它对我不起作用,因为我只能使用 FilterParameter 中的一个字段,即 PRODUCE only 而不是动态的

   func filter(fu []GRN, su []FilterParameter) (out []GRN) {
        f := make(map[string]struct{}, len(su))
        for _, u := range su {
            f[u.PRODUCE] = struct{}{}
        }
        for _, u := range fu {
            if _, ok := f[u.PRODUCE]; ok {
                out = append(out, u)
            }
        }
        return
    }

1 个答案:

答案 0 :(得分:1)

你不能真正做你想做的事,因为它不可能迭代 struct 的字段(可能带有反射)。对于另一种方法,您可以 使用 maps 而不是 structs,或者更简单,如果你可以明确地使用 函数参数中你关心的字段:

package main
import "fmt"
type GRN struct { DocType, GRNNO, PRID, PRODUCE, VARIETY string }

func filter(in []GRN, produce, variety string) []GRN {
   var out []GRN
   for _, each := range in {
      if each.PRODUCE == produce && each.VARIETY == variety {
         out = append(out, each)
      }
   }
   return out
}

func main() {
   manyGRNUsers := []GRN{
      {"GRNAsset","GRN0000109","PRFAINAPKR0086","Sweetcorn","CP2"},
      {"GRNAsset","GRN0000110","PRFAINAPKR0087","Sweetcorn","CP1"},
      {"GRNAsset","GRN0000112","PRFAINAPKR0087", "Sweetcorn","CP2"},
      {"GRNAsset","GRN0000113","PRFAINAPKR0089","Apple","Gala"},
   }
   out := filter(manyGRNUsers, "Sweetcorn", "CP2")
   fmt.Println(out)
}