Skip to content

Instantly share code, notes, and snippets.

@DavidVaini
Created November 13, 2013 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidVaini/7456823 to your computer and use it in GitHub Desktop.
Save DavidVaini/7456823 to your computer and use it in GitHub Desktop.
Find the first element in an array that matches the search criteria.
package main
import (
"reflect"
"log"
)
type Part struct {
Id int
UPC string
Desc string
}
// Find the first struct in an array that matches search criteria.
// Search Criteria includes the field on the struct you are searching and the value of field you are searching.
// For example: You could pass in an array of Parts. You want to find the first part with an ID of 11000. Method call would be something like:
//
// var result = finder.FindFirst(listOfParts, "Id", 11000) // the array can be any type, the field is represented by a string, and the value you are searching for can be any type.
//
// if result != nil {
// partObj := result.(part) // .(part) casts it to whatever type object you expect to return (same as array type)
// log.Println(partObj.UPC) // outputs the UPC for the part with an Id of 11000.
// }
// This approach is similar to c# LINQ statement: listOfParts.Where(x=>x.Id == 11000).FirstOrDefault()
func FindFirst(arrayToSearch interface{}, field string, value interface{}) (singleObj interface{}) {
slice := reflect.ValueOf(arrayToSearch)
vals := make([]reflect.Value, slice.Len(), slice.Len())
for i := range vals {
vals[i] = reflect.Indirect(reflect.Indirect(slice.Index(i)))
}
for _, t := range vals {
val := t.FieldByName(field).Interface()
var stringVal interface{}
stringVal = value
if val == stringVal {
singleObj = t.Interface()
return
}
}
return
}
func main() {
var listOfParts []Part
var partToSearch Part
partToSearch.Id = 12345
partToSearch.UPC = "0023423"
partToSearch.Desc = "awesomeo"
var partToSearch2 Part
partToSearch2.Id = 11123
partToSearch2.UPC = "00Jdl3i8"
partToSearch2.Desc = "notSoAwesome"
listOfParts = append(listOfParts, partToSearch, partToSearch2)
temp := ""
var result = FindFirst(listOfParts, "Id", 11123)
if result != nil {
partObj := result.(Part)
temp = partObj.UPC
log.Println("UPC is: " + temp)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment