Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all matches in Go array

Tags:

go

I have an array of structs (struct detailed at bottom)

I want to find all the structs that match certain values for, example, leg and site.

So if leg=101 and site=1024A give back all the structs that match these criteria.

What is the Go manner for doing this?

type JanusDepth struct {
    dataset string
    ob      string
    leg     string  
    site    string  
    hole    string
    age     float64
    depth   float64
    long    float64
    lat     float64
}
like image 643
Douglas Fils Avatar asked Oct 11 '13 16:10

Douglas Fils


People also ask

How to access array elements in Go language?

In Go language, arrays are mutable, so that you can use array [index] syntax to the left-hand side of the assignment to set the elements of the array at the given index. You can access the elements of the array by using the index value or by using for loop. In Go language, the array type is one-dimensional.

How do you find all matches in a string in Python?

finditer method The re.finditer () works exactly the same as the re.findall () method except it returns an iterator yielding match objects matching the regex pattern in a string instead of a list. It scans the string from left-to-right, and matches are returned in the iterator form. Later, we can use this iterator object to extract all matches.

How to index an array in Golang?

In an array, you are allowed to store zero or more than zero elements in it. The elements of the array are indexed by using the [] index operator with their zero-based position, means the index of the first element is array [0] and the index of the last element is array [len (array)-1]. In Go language, arrays are created in two different ways:

What is matching in Golang?

So let’s dive deeper into the concept of matching in GoLang. regexp (regular expressions) is all about string/pattern matching. Every function, every part of regexp functions somewhere requires text matching.


2 Answers

Dead simple:

leg      := "101"
site     := "1024A"
filtered := []JanusDepth{}

for _, e := range MyArrayOfStructs {
    if(e.leg == leg && e.site == site) {
        filtered = append(filtered, e)
    }
}

// filtered contains your elements
like image 105
thwd Avatar answered Oct 04 '22 03:10

thwd


If your data is ordered on one key, then you can use http://golang.org/pkg/sort/#Search to do a binary search, which is better for performance if the amount of data is moderate to large.

like image 21
Jeff Allen Avatar answered Oct 04 '22 02:10

Jeff Allen