How to find the last index value in slice of bytes in Golang?
Last Updated :
29 Oct, 2024
In Go, a slice is a flexible data structure that stores a variable-length sequence of elements of the same type. The LastIndex()
function from the bytes
package returns the last index of a specified value in a byte slice, or -1 if the value is not found.
Example
package main
import (
"bytes"
"fmt"
)
func main() {
// Define the slice of bytes
slice := []byte("GeeksforGeeks, Learning Go")
// Define the byte to search for
searchByte := []byte("e")
// Find the last index of the specified byte
lastIndex := bytes.LastIndex(slice, searchByte)
// Display the result
fmt.Printf("\n", searchByte, lastIndex)
}
Syntax
func LastIndex(ori_slice, sep_ []byte) int # Using the bytes.LastIndex
Function
Using the bytes.LastIndex
Function
The simplest way to find the last index of a specified byte slice is to use the LastIndex
function from the bytes
package.
Go
package main
import (
"bytes"
"fmt"
)
func main() {
originalSlice := []byte("Welcome to GeeksforGeeks")
searchSlice := []byte("ks")
lastIndex := bytes.LastIndex(originalSlice, searchSlice)
fmt.Printf("%s: %d\n", searchSlice, lastIndex)
}
Other method's: