How to remove element of struct array in loop in golang

前端 未结 4 1709
谎友^
谎友^ 2020-12-29 06:01

Problem

I have array of structs:

type Config struct {
  Applications []Application
}

Note: Config - is a struct fo

4条回答
  •  自闭症患者
    2020-12-29 06:37

    This question is a bit older but I haven't found another answer on StackOverflow which mentions the following trick from the Slice Tricks to filter a list:

    b := a[:0]
    for _, x := range a {
        if f(x) {
            b = append(b, x)
        }
    }
    

    So in this case a function which deletes certain elements could look like this:

    func removeApplications(apps []Applications) []Applications {
        filteredApps := apps[:0]
        for _, app := apps {
            if !removeApp {
                filteredApps = append(filteredApps, app)
            }
        }
        return filteredApps
    }
    

提交回复
热议问题