Trim a slice of bytes in Golang

In Go, you can trim a slice of bytes using the bytes.Trim() function from the bytes package. This function removes specified leading and trailing bytes from the slice.

Here’s how you can trim a slice of bytes:

package main

import (

func main() {
    // Creating a slice of bytes
    data := []byte{' ', ' ', 'H', 'e', 'l', 'l', 'o', ' ', ' ', ' '}

    // Trimming leading and trailing spaces
    trimmedData := bytes.Trim(data, " ")

    // Converting the trimmed slice to string and printing it
    fmt.Println("Trimmed Data:", string(trimmedData))

Output :

Trimmed Data: Hello

In this example, we import the bytes package and create a slice of bytes named data that contains leading and trailing spaces. We use bytes.Trim() to remove those leading and trailing spaces from the slice. The Trim() function returns a new slice, so the original data slice remains unchanged.

You can specify the characters you want to trim in the second argument of the bytes.Trim() function. In this case, we passed " " to trim spaces.

Keep in mind that trimming does not modify the original slice; it creates a new slice with the specified characters removed.