Loading, please wait...

A to Z Full Forms and Acronyms

Explain How to Split a Slice of bytes in Go Language | Go Programming Tutorial

In this article, you will learn how to split a slice of bytes in Go Programming Language. 

Explain How to Split a Slice of bytes in Go Language | Go Programming Tutorial

In this article, you will learn how to split a slice of bytes in 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 GoLang slice of bytes, the user is allowed to split the given slice using a split() function. The split() function helps in splitting a slice of the byte into all the sub-slices separators and returns a slice that contains all these sub-slices. It is defined under the bytes package so, the user has to import the bytes package in the program for accessing split() function. 
Syntax:
func Split(org_slice, dif [ ]byte) [ ] [ ] byte
Here, org_slice is the slice of bytes and dif is the separator. If the dif is empty, then it will split after the UTF-8 sequence.  

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)
  
    // Splitting the slice of bytes
    // Using Split function
    res1 := bytes.Split(s_1, []byte("link"))
    res2 := bytes.Split(s_2, []byte(""))
    res3 := bytes.Split(s_3, []byte("%"))
  
    // Display the results
    fmt.Printf("\n\nAfter Splitting:")
    fmt.Printf("\nSlice 1: %s", res1)
    fmt.Printf("\nSlice 2: %s", res2)
    fmt.Printf("\nSlice 3: %s", res3)
  
}
 
OUTPUT:
Original Slice:
Slice 1: !TutorialsLink#
Slice 2: Ebooks
Slice 3: %H%o%m%e%
 
After Splitting:
Slice 1: [! T u t o r i a l s #]
Slice 2: [E b o o k s]
Slice 3: [H o m e]
A to Z Full Forms and Acronyms