Home >Backend Development >Golang >How to skip values in slice if condition is matched first time
php editor Banana will introduce to you how to skip the value of the first matching condition in the slice. During development, we often need to deal with slices of arrays or strings, but sometimes we want to skip the first value in the slice that meets a specific condition. This may be because we only care about subsequent matches, or we only need to process values after a specific position. Next, we'll explore several solutions to help you achieve this goal.
How to skip values in a slice if the condition matches once.
func main() { cloud := []string{"moon", "earth", "moon-light"} for _, value := range cloud { if strings.Contains(value, "mo") { fmt.Println("print1") } else if strings.Contains(value, "ear") { fmt.Println("print2") } } }
Output: print 1 Print 2 Print 1
Expected output: print 1 Print 2
Thanks!
You can use the map to find out if a specific situation occurs. It's better than using variables because it allows you to track a large number of conditions without causing any confusion. Here is an example of what you want:
cloud := []string{"moon", "earth", "moon-light"} var conditionTracker = make(map[string]bool) for _, value := range cloud { if _, ok := conditionTracker["first_condition"]; !ok && strings.Contains(value, "mo") { conditionTracker["first_condition"] = true fmt.Println("print1") } else if _, ok := conditionTracker["second_condition"]; !ok && strings.Contains(value, "ear") { conditionTracker["second_condition"] = true fmt.Println("print2") } }
The above is the detailed content of How to skip values in slice if condition is matched first time. For more information, please follow other related articles on the PHP Chinese website!