Datsik
Datsik

Reputation: 14824

How can I get a slices new index after a goroutine channel has mutated the slice?

I'm wondering how I can get an elements new index in a slice, I have a function that gets applications from a database, and queries for certain ones (for filtering) but when I query for ones and I get ones I don't need, I'm trying to remove them from the slice so that only the wanted ones make it to the view. It's working but I'm having a problem with the index's in the goroutines are the older index's so when it trys to remove the element from the slice it panics: Anyways here is my code:

// ListApplications will list the applications
func ListApplications(w http.ResponseWriter, r *http.Request) {
    session := common.Sesh(r)
    urlParse, err := url.ParseRequestURI(r.RequestURI)
    vals := urlParse.Query()

    if err != nil {
        log.Println(err)
    }
    if lvl, ok := session.Values["user_level"]; !ok || lvl.(int) < 3 {
        http.Redirect(w, r, "/", 401)
        return
    }

    db := common.Db()

    type UserResp struct {
        Action string
        I      int
        User   common.User
    }
    apps := []common.Application{}
    resp := make(chan UserResp)
    db.Order("accepted asc").Order("created_at asc").Find(&apps)
    var wg sync.WaitGroup
    for i, app := range apps {
        wg.Add(1)
        go func(i int, app common.Application) {
            user := common.User{}
            if vals.Get("class") != "" {
                db.Preload("Characters", "character_class = ?", vals.Get("class")).Model(&app).Related(&user)
                if len(user.Characters) == 0 {
                    resp <- UserResp{"remove", i, user}
                } else {
                    resp <- UserResp{"add", i, user}
                }
                wg.Done()
                return
            }

            db.Preload("Characters").Model(&app).Related(&user)
            log.Println(user)
            resp <- UserResp{"add", i, user}
            wg.Done()
        }(i, app)
    }

    go func() {
        wg.Wait()
        close(resp)
    }()

    for user := range resp {
        switch user.Action {
        case "add":
            apps[user.I].User = user.User
        case "remove":
        log.Println(len(apps), user.I)
            apps = append(apps[:user.I], apps[user.I+1:]...)
        }
    }

    common.View(w, r, "/application/list", &struct {
        Title string
        Apps  []common.Application
    }{"Viewing Applications", apps})
}

The for user := range resp is where I'm trying to delete under the "remove" action. But like I said, the index getting passed through on the channel is out dated sometimes so how can I maintain a persistent index in my goroutines

Upvotes: 0

Views: 330

Answers (1)

Zippo
Zippo

Reputation: 16420

Don't range over a slice if you want to remove elements from it.

Instead, loop over the slice by index:

// Removes 2 from slice.
slice := []int{1,2,3}
for i := 0; i < len(slice); i++ {
    if slice[i] == 2 {
        slice = append(slice[:i], slice[i+1:]...)
        i--
    }
}
fmt.Println(slice) // [1 3]

The point is bringing the index cursor back by one (so it won't go forward) after you've removed the current element.

Upvotes: 2

Related Questions