Loading, please wait...

A to Z Full Forms and Acronyms

Explain How to trim a Slice of Bytes in Go Language | Go Programming Tutorial

In this article, you will learn about how to trim a Slice of Bytes in the Go Programming Language. 

Explain How to trim a Slice of Bytes in Go Language | Go Programming Tutorial

In this article, you will learn about how to trim a Slice of Bytes in the Go Programming Language. 

A slice is a kind of data type which is similar to an array which is used to hold the items of the same data type. The only difference between array and slice data types is that slice can vary in size dynamically but it is not feasible in arrays. 
In the Go slice of bytes, the users are allowed to trim all the leading and trailing UTF-8-encoded code points from the given slice using the Trim() function. This function returns a sub-part of the slice of the original slice by slicing off all leading and trailing UTF-8-encoded code points which are mentioned in the given string. If the particular slice of byte does not have the particular string in it, then this function will return the original slice without any slice. It is defined under the bytes package so, the user has to import the bytes package in your program for accessing the Trim() function
Syntax:
func Trim(org_slice[ ] byte, sub_slice string) [ ]byte 
Here, org_slice is the original slice of the bytes and sub_slice is the string that you want to trim in the particular slice. 

Example:

package main 
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Create and initializethe slice of bytes using shorthand declaration
    s_1 := []byte{'!','T', 'u', 't', 'o', 'r', 'i',  
                 'a', 'l', 's', 'L', 'i', 'n', 'k', '#'} 
    s_2 := []byte{'*','E', 'b', 'o', 'o', 'k', 's', '^'}
    s_3 := []byte{'@','H', 'o', 'm', 'e', '@'}
  
    // Displaying slices
    fmt.Println("Original Slice:")
    fmt.Printf("Slice 1: %s", s_1)
    fmt.Printf("\nSlice 2: %s", s_2)
    fmt.Printf("\nSlice 3: %s", s_3)
  
    res1 := bytes.Trim(s_1, "!#")
    res2 := bytes.Trim(s_2, "*^")
    res3 := bytes.Trim(s_3, "@")
  
    // Display the results
    fmt.Printf("\nNew Slice:\n")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
}
 
OUTPUT:
Orginial Slice: 
Slice 1: !TutorialsLink#
Slice 2: *Ebooks^
Slice 3: @Home@
New Slice:
Slice 1: TutorialsLink
Slice 2: Ebooks
Slice 3: Home
A to Z Full Forms and Acronyms