Golang中的嵌套循环

I have two arrays: Cart and Promotions, I need to find out what promotions can be applied to the cart.

Promotions consist of Affectee and Affected, so what I do is search in my Cart array to see if I have any Affectee and if I do then I search for any Affected and then apply the promo. This however, forces me to implement three nested loops which is not ideal for an API that has a 3 second timeout.

I'm wondering if golang's arrays has something or if there's a way I can make this faster

Here's my code:

  OUTER:
  for i, item := range cartSession.Cart {
    for _, promo := range promotions {
      if item.Name == promo.Affected.Name {
        // If an item in the cart can be affected by the promo
        // then start investigating if we have the affectee
        if item.Name == promo.Affectee.Name {
          // If the item is the affected and affectee
          if promo.Affected.CostPtg != 0 {
            cartSession.Cart[i].Cost *= promo.Affected.CostPtg
          } else {
            cartSession.Cart[i].Cost = promo.Affected.CostFixed
          }
          continue OUTER
        } else {
          for _, subItem := range cartSession.Cart {
            if subItem.Name == promo.Affectee.Name {
              // We have both the affected & affectee
              // time to apply the promo affect
              if promo.Affected.CostPtg != 0 {
                cartSession.Cart[i].Cost *= promo.Affected.CostPtg
              } else {
                cartSession.Cart[i].Cost = promo.Affected.CostFixed
              }
              continue OUTER
            }
          }
        }
      }
    }
  }

One way you may be able to speed this up it is lookup items in the cart using a map, instead of iterating through them. Create the map like this:

cartMap := make(map[string]*CartType, len(cartSession.Cart))
for i := range cartSession.Cart {
    cartMap[cartSession.Cart[i].Name] = cartSession.Cart[i]
}

Then after building the map, you can look in the cart to see if it contains the affected and affectee, like this:

for i := range promotions {
    // See if affected item is in cart                                      
    affected := promotions[i].Affected
    cartItem, ok := cartMap[affected.Name]
    if !ok {
        // Did not find affected                                            
        continue
    }
    // See if affectee is in cart                                           
    affectee := promotions[i].Affectee
    if _, ok = cartMap[affectee.Name]; !ok {
        // Did not find affectee                                            
        continue
    }
    // Apply promotion                                                      
    if affected.CostPtg != 0 {
        cartItem.Cost *= affected.CostPtg
    } else {
        cartItem.Cost = affected.CostFixed
    }
}