To reverse a byte slice in Go using the bytes
package, you can use the Reverse
function along with the bytes
package. Here's an example:
package main
import (
"bytes"
"fmt"
)
func main() {
byteSlice := []byte{'a', 'b', 'c', 'd', 'e'}
reversedSlice := reverse(byteSlice)
fmt.Println(string(reversedSlice)) // Output: edcba
}
func reverse(input []byte) []byte {
result := make([]byte, len(input))
copy(result, input)
bytes.Reverse(result)
return result
}
In this example, we define a reverse
function that takes in a byte slice as input and returns a reversed byte slice.
To reverse the byte slice, we first create a new byte slice called result
with the same length as the input slice and copy the input slice values into it.
Then, we use the bytes.Reverse
function to reverse the byte slice in-place.
Finally, we return the reversed byte slice.