Menu Close

Go – Concatenate byte slices with separator in go

bytes.Join() function is used to concatenate byte slices with separator in go. This function creates the new byte slice and return it.

Join() built-in function of bytes package concatenates the elements of array of byte slices and create a new byte slice.

bytes.Join() function prototype:

func Join(s [][]byte, sep []byte) []byte

Input parameters:
s: Array byte slices
sep: byte slice separator to be placed between the array of byte slices

Return:
It returns the newly created byte slice.

Explanation on concatenate byte slices with separator in go:

1)
s := [][]byte{[]byte("John"), []byte("is"), []byte("doing"), []byte("well")}
sep := []byte("-")

Output: "John-is-doing-well"

2)
s := [][]byte{[]byte("去"), []byte("是")}
sep := []byte(": ")

Output: "去: 是"

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := [][]byte{[]byte("John"), []byte("is"), []byte("doing"), []byte("well")}
    sep := []byte("-")
    
    fmt.Printf("%q", bytes.Join(s, sep))
    
	
	s = [][]byte{[]byte{10}, []byte{20}, []byte{30}}
    sep = []byte("---")
    
    fmt.Printf("\n%q", bytes.Join(s, sep))
    
    
    s = [][]byte{[]byte("去"), []byte("是")}
    sep = []byte(": ")
    
    fmt.Printf("\n%q", bytes.Join(s, sep))
    
    
    s = [][]byte{[]byte{1, 2}, []byte{3, 4}}
    sep = []byte(" :: ")
    
    fmt.Printf("\n%q", bytes.Join(s, sep))
}

Output:

"John-is-doing-well"

"\n---\x14---\x1e"

"去: 是"

"\x01\x02 :: \x03\x04"

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *