In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.
In the Go slice of bytes, you are allowed to join the elements of the byte slice with the help of Join() function. Or in other words, Join function is used to concatenate the elements of the slice and return a new slice of bytes which contain all these joined elements separated by the given separator. It is defined under the bytes package so, you have to import bytes package in your program for accessing Join function.
Syntax:
func Join(slice_1 [][]byte, sep []byte) []byte
Here, sep is the separator placed between the elements of the resulting slice. Let us discuss this concept with the help of the examples:
Example 1:
package main
import (
"bytes"
"fmt"
)
func main() {
name := [][]byte{[]byte( "Sumit" ),
[]byte( "Kumar" ),
[]byte( "Singh" )}
sep := []byte( "-" )
fmt.Printf( "First Name: %s" , name[0])
fmt.Printf( "\nMiddle Name: %s" , name[1])
fmt.Printf( "\nLast Name: %s" , name[2])
full_name := bytes.Join(name, sep)
fmt.Printf( "\n\nFull name of the student: %s" , full_name)
}
|
Output:
First Name: Sumit
Middle Name: Kumar
Last Name: Singh
Full name of the student: Sumit-Kumar-Singh
Example 2:
package main
import (
"bytes"
"fmt"
)
func main() {
slice_1 := [][]byte{[]byte( "Geeks" ), []byte( "for" ), []byte( "Geeks" )}
slice_2 := [][]byte{[]byte( "Hello" ), []byte( "My" ),
[]byte( "name" ), []byte( "is" ), []byte( "Bongo" )}
fmt.Println( "Slice(Before):" )
fmt.Printf( "Slice 1: %s " , slice_1)
fmt.Printf( "\nSlice 2: %s" , slice_2)
res1 := bytes.Join(slice_1, []byte( " , " ))
res2 := bytes.Join(slice_2, []byte( " * " ))
res3 := bytes.Join([][]byte{[]byte( "Hey" ), []byte( "I" ),
[]byte( "am" ), []byte( "Apple" )}, []byte( "+" ))
fmt.Println( "\n\nSlice(after):" )
fmt.Printf( "New Slice_1: %s " , res1)
fmt.Printf( "\nNew Slice_2: %s" , res2)
fmt.Printf( "\nNew Slice_3: %s" , res3)
}
|
Output:
Slice(Before):
Slice 1: [Geeks for Geeks]
Slice 2: [Hello My name is Bongo]
Slice(after):
New Slice_1: Geeks , for , Geeks
New Slice_2: Hello * My * name * is * Bongo
New Slice_3: Hey+I+am+Apple
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Aug, 2019
Like Article
Save Article