What is the IndexFunc function in Golang?

Overview

The IndexFunc function is used to find the index of the first appearance of a Unicode code character in a string, such that it satisfies the provided function.

To use this function, we must import the strings package in our file and access the IndexFunc function within it, using the . notation (string.IndexFunc).

Function definiton

Here is the definition of the IndexFunc function:

func IndexFunc (str string, fun func(rune) bool) int

Parameters

The IndexFunc function takes two arguments:

  • str: This is an argument of type string. It represents the list of characters that we want to search.

  • fun: This argument represents the function that takes a rune as an argument and returns a boolean variable.

Return value

The IndexFunc function returns the index where it finds the first instance of a character that the function fun returns True on. If there is no such character in the whole string, then -1 is returned.

Code

In the code given below, we use the IndexFunc function to find the position of the first Greek letter that appears in a string:

package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
fun := func(r rune) bool {
return unicode.Is(unicode.Greek, r)
}
str := "The greek letter α is used often in mathematics"
x := strings.IndexFunc(str, fun)
fmt.Println("a greek alphabet appears at position: ", x)
}

Note: The unicode package is imported here, so that we can use the unicode.Is function. This function checks if a certain rune value is present in a list of Unicode values. In this case, the list consists of all Greek characters, which we get by using unicode.Greek.

The following example demonstrates a case where no character in the string satisfies the given function:

package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
fun := func(r rune) bool {
return unicode.Is(unicode.Greek, r)
}
str := "Educative Inc."
x:= strings.IndexFunc(str, fun)
if x == -1{
fmt.Println("could not find any greek alphabets in : \"",str, "\"" )
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources