golang determines whether the element is in the array
As we all know, there is no python-like in golang to determine whether an element exists in a list. The alternative is to put the list in the map and determine whether the element exists in the map.
// The elements "amber", "jack" in the list are knownarr := [...]string{"amber","jack"} // Initialize mapvar set map[string]struct{} set = make(map[string]struct{}) // The above two parts can be replaced by set := make(map[string]struct{}) // Pass the list content into the map, only judged based on the key, so you don't need to care about the value, and use struct{}{} to represent itfor _, value := range arr{ set[value] = struct{}{} } // Check if the element is in mapif _, ok := set["amber"];ok { ("amber is in the list") } else { ("amber is not in the list") }
golang determines whether a target element is in the target array
- The target array can only contain basic types such as shaping, strings, and boolean types.
- The target element can only contain basic types such as shaping, string, and boolean types.
- Non-interface arrays need to be converted to the corresponding interface array first.
- The conversion of the other basic types can be realized according to the idea
import "reflect" func FolatArray2Interface(array []float32) []interface{} { var goalArray []interface{} for _, value := range array { goalArray = append(goalArray, value) } return goalArray } func IntArray2Interface(array []int) []interface{} { var goalArray []interface{} for _, value := range array { goalArray = append(goalArray, value) } return goalArray } func StringArray2Interface(array []string) []interface{} { var goalArray []interface{} for _, value := range array { goalArray = append(goalArray, value) } return goalArray } func InArray(array []interface{}, element interface{}) bool { // Implement to find out whether the shaping, string type and bool type are in the array if element == nil || array == nil { return false } for _, value := range array { // First, determine whether the types are consistent if (value).Kind() == (element).Kind() { // Is the comparison value consistent if value == element { return true } } } return false }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.