# How to find the last index value of any element in slice of bytes in Golang?

In Go, finding the last index value of an element in a slice of bytes can be a common requirement while working with strings and byte arrays. Fortunately, there is a built-in function in Go that allows us to find the last index value of an element in a slice of bytes.

In this article, we will discuss how to find the last index value of any element in a slice of bytes in Go.

## Syntax of LastIndexByte Function

The built-in function LastIndexByte returns the index of the last occurrence of the given byte c in the slice of bytes s, or -1 if c is not present in s.

func LastIndexByte(s []byte, c byte) int


## Example of Using LastIndexByte Function

Let's see how we can use the LastIndexByte function to find the last index value of an element in a slice of bytes.

package main

import (
"bytes"
"fmt"
)

func main() {
s := []byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
c := byte('f')

lastIndex := bytes.LastIndexByte(s, c)

fmt.Printf("The last index of '%c' in %v is %d\n", c, s, lastIndex)
}


## Output

The last index of 'f' in [97 98 99 100 101 102 103 104 105 106] is 5


In the above example, we have a slice of bytes s that contains the values from 'a' to 'j'. We want to find the last index value of the byte 'f' in the slice of bytes s.

To do that, we pass the slice of bytes s and the byte 'f' as arguments to the LastIndexByte function. The function returns the index of the last occurrence of the byte 'f' in the slice of bytes s.

Finally, we print the last index value of the byte 'f' in the slice of bytes s.

## Conclusion

In this article, we discussed how to find the last index value of any element in a slice of bytes in Go using the built-in LastIndexByte function. By using this function, we can easily find the last occurrence of a specific byte in a byte array.

Updated on: 05-May-2023

79 Views