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


Slices of bytes in Golang are used to represent a sequence of bytes. Finding the index of the last element in a slice of bytes can be useful in many scenarios. In this article, we will discuss how to find the last index value in a slice of bytes in Golang.

Steps to Find The Last Index Value in a Slice of Bytes in Golang

  • Create a slice of bytes.

  • Get the length of the slice using the len() function.

  • Traverse the slice from the end using a loop.

  • Compare each element of the slice with the desired element.

  • If the element is found, return the index.

  • If the element is not found, return -1.

Let's see an example to understand these steps −

Example

package main

import "fmt"

func main() {
   // create a slice of bytes
   byteSlice := []byte{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'}
   
   // get the length of the slice
   length := len(byteSlice)
   
   // traverse the slice from the end using a loop
   for i := length - 1; i >= 0; i-- {
      // compare each element of the slice with the desired element
      if byteSlice[i] == 'd' {
         // if the element is found, return the index
         fmt.Println("The last index of 'd' in the slice is:", i)
         return
      }
   }
   
   // if the element is not found, return -1
   fmt.Println("The element 'd' is not present in the slice.")
}

Output

The last index of 'd' in the slice is: 10

Explanation

In this example, we created a slice of bytes and stored the string "Hello World!" in it. We then got the length of the slice using the len() function. We traversed the slice from the end using a loop and compared each element of the slice with the desired element 'd'. When we found the element 'd', we returned the index. If the element 'd' is not present in the slice, we returned -1.

Conclusion

Finding the last index value in a slice of bytes can be useful in many scenarios. In this article, we discussed how to find the last index value in a slice of bytes in Golang. We also saw an example to understand the steps involved in finding the last index value.

Updated on: 05-May-2023

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements