Find Index by Value in Go

Posted by yhuang
Public (Editable by Users)
Go
Edit
package main

import (
	"fmt"
	"strings"
)

func FindStrIdx(list []string, pred func(s string) bool) int {
	for i, s := range list {
		if pred(s) {
			return i
		}
	}
	return -1
}

func main() {

	list := []string{"slice", "of", "strings"}
	res := FindStrIdx(list, func(s string) bool {
		return strings.HasPrefix(s, "o")
	})
	fmt.Println(res)
}