funcindexOf[Tcomparable](s[]T,xT)(int,error){fori,v:=ranges{// v and x are type T, which has the comparable// constraint, so we can use == here.ifv==x{returni,nil}}return0,errors.New("not found")}
// Signed is a constraint that permits any signed integer type.// If future releases of Go add new predeclared signed integer types,// this constraint will be modified to include them.typeSignedinterface{~int|~int8|~int16|~int32|~int64}// Unsigned is a constraint that permits any unsigned integer type.// If future releases of Go add new predeclared unsigned integer types,// this constraint will be modified to include them.typeUnsignedinterface{~uint|~uint8|~uint16|~uint32|~uint64|~uintptr}// Integer is a constraint that permits any integer type.// If future releases of Go add new predeclared integer types,// this constraint will be modified to include them.typeIntegerinterface{Signed|Unsigned}
funcindexOfInteger[Tconstraints.Integer](s[]T,xT)(int,error){fori,v:=ranges{// v and x are type T, which has the comparable// constraint, so we can use == here.ifv==x{returni,nil}}return0,errors.New("not found")}
funcindexOfFloat[Tconstraints.Float](s[]T,xT)(int,error){fori,v:=ranges{// v and x are type T, which has the comparable// constraint, so we can use == here.ifv==x{returni,nil}}return0,errors.New("not found")}
packagemainimport("errors""fmt""golang.org/x/exp/slices")funcindexOf[Tcomparable](s[]T,xT)(int,error){fori,v:=ranges{// v and x are type T, which has the comparable// constraint, so we can use == here.ifv==x{returni,nil}}return0,errors.New("not found")}funcmain(){i,err:=indexOf([]string{"apple","banana","pear"},"banana")fmt.Println(i,err)i,err=indexOf([]int{1,2,3},3)fmt.Println(i,err)fmt.Println(slices.Index([]string{"apple","banana","pear"},"banana"))}
// Index returns the index of the first occurrence of v in s,// or -1 if not present.funcIndex[Ecomparable](s[]E,vE)int{fori,vs:=ranges{ifv==vs{returni}}return-1}
// BinarySearch searches for target in a sorted slice and returns the smallest// index at which target is found. If the target is not found, the index at// which it could be inserted into the slice is returned; therefore, if the// intention is to find target itself a separate check for equality with the// element at the returned index is required.funcBinarySearch[Elemconstraints.Ordered](x[]Elem,targetElem)int{returnsearch(len(x),func(iint)bool{returnx[i]>=target})}funcsearch(nint,ffunc(int)bool)int{// Define f(-1) == false and f(n) == true.// Invariant: f(i-1) == false, f(j) == true.i,j:=0,nfori<j{h:=int(uint(i+j)>>1)// avoid overflow when computing h// i ≤ h < jif!f(h){i=h+1// preserves f(i-1) == false}else{j=h// preserves f(j) == true}}// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.returni}
// ToBool convert any type to booleanfuncToBool(valueinterface{})bool{switchvalue:=value.(type){casebool:returnvaluecaseint:ifvalue!=0{returntrue}returnfalse}returnfalse}