find the last index of a substring in a string in go

To find the last index of a substring in a string in Go, we can use the strings.LastIndex function. This function returns the index of the last instance of the provided substring in the given string. If the substring is not found, it returns -1.

Here's an example:

main.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello world, how are you"
	substr := "o"
	lastIndex := strings.LastIndex(str, substr)

	fmt.Println(lastIndex)
}
180 chars
15 lines

In this example, we have a string "Hello world, how are you" and we want to find the last index of the substring "o". We pass both values to strings.LastIndex function and it returns the index of 15, which is the last index of "o" in the given string.

gistlibby LogSnag