Fragment Description:



Is 'element' contained in a slice of structs? A simple contains? utility, can be useful.


containsElemThisSliceOfStruct

Go Playground

Last update, on 2015, Mon 9 Nov, 17:20:13

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    // "reflect"  // to be uncommented when... see below
)

type PlaygroundItem struct {
    SourceName string
    CodeHash   interface{}
}
type aS struct {
    Id   int
    name string
}

var (
    items PlaygroundItems

    aS1 = aS{Id: 1, name: "gofragments"}
    aS2 = &aS{Id: 1, name: "gofragments"}
)

type PlaygroundItems []*PlaygroundItem

func main() {
    p1 := &PlaygroundItem{
        SourceName: "name-1",
        CodeHash:   "k9CxqTMS0K",
    }
    p2 := &PlaygroundItem{
        SourceName: "name-2",
        CodeHash:   6,
    }
    p3 := &PlaygroundItem{
        SourceName: "name-3",
        CodeHash:   aS1,
    }

    items = append(items, p1, p2, p3)

    exist, _ := containsCodeHash(items, aS1)
    fmt.Println("exist as1 in items:\t", exist)

    exist, _ = containsCodeHash(items, aS2)
    fmt.Println("exist as2 in items:\t", exist)

    exist, _ = containsCodeHash(items, 6)
    fmt.Println("exist 6 in items:\t", exist)

    exist, _ = containsCodeHash(items, "k9CxqTMS0K")
    fmt.Println("exist 'k9CxqTMS0K' in items:\t", exist)

}
func containsCodeHash(items PlaygroundItems, elem interface{}) (bool, int) {
    for index, item := range items {
        // what '==' means? see: http://research.swtch.com/interfaces
        // try also the following (uncomment "reflect" above)
        // if  reflect.DeepEqual(item.CodeHash, elem) {
        if item.CodeHash == elem {
            return true, index
        }
    }
    return false, 0
}

/* Expected Output
exist as1 in items:     true
exist as2 in items:     false
exist 6 in items:   true
exist 'k9CxqTMS0K' in items:  true
*/



Comments