Home »
Golang »
Golang Reference
Golang bytes.Join() Function with Examples
Golang | bytes.Join() Function: Here, we are going to learn about the Join() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 24, 2021
bytes.Join()
The Join() function is an inbuilt function of the bytes package which is used to concatenate the elements of the slice of byte slices (s) to create a new byte slice, the elements concatenate with the given separator.
It accepts two parameters (s [][]byte, sep []byte) and returns a new byte slice.
Syntax
func Join(s [][]byte, sep []byte) []byte
Parameters
- s : The slice of byte slices whose elements are to be concatenated with the sep.
- sep : The byte slice which is used to be placed as a separator between the elements of s.
Return Value
The return type of the bytes.Join() function is []byte, it returns a new concatenated byte slice.
Example 1
// Golang program to demonstrate the
// example of bytes.Join() function
package main
import (
"bytes"
"fmt"
)
func main() {
str := [][]byte{
[]byte("iPhone"),
[]byte("iWatch"),
[]byte("iPad")}
fmt.Printf("%q\n", str)
// Separated by " "
fmt.Printf("%s\n", bytes.Join(str, []byte(" ")))
// Separated by ", "
fmt.Printf("%s\n", bytes.Join(str, []byte(", ")))
// Separated by "---"
fmt.Printf("%s\n", bytes.Join(str, []byte("---")))
}
Output:
["iPhone" "iWatch" "iPad"]
iPhone iWatch iPad
iPhone, iWatch, iPad
iPhone---iWatch---iPad
Example 2
// Golang program to demonstrate the
// example of bytes.Join() function
package main
import (
"bytes"
"fmt"
)
func main() {
cars := [][]byte{[]byte("Honda-Amaze"),
[]byte("Honda-City"),
[]byte("Eercedes-E200")}
fmt.Printf("Cars: %q\n", cars)
fmt.Printf("Car 1: %q\n", cars[0])
fmt.Printf("Car 2: %q\n", cars[1])
fmt.Printf("Car 3: %q\n", cars[2])
// Separated by " "
fmt.Printf("%s\n", bytes.Join(cars, []byte(" ")))
// Separated by ", "
fmt.Printf("%s\n", bytes.Join(cars, []byte(", ")))
// Separated by "---"
fmt.Printf("%s\n", bytes.Join(cars, []byte("---")))
}
Output:
Cars: ["Honda-Amaze" "Honda-City" "Eercedes-E200"]
Car 1: "Honda-Amaze"
Car 2: "Honda-City"
Car 3: "Eercedes-E200"
Honda-Amaze Honda-City Eercedes-E200
Honda-Amaze, Honda-City, Eercedes-E200
Honda-Amaze---Honda-City---Eercedes-E200
Golang bytes Package »