Golang 如何连接字节片的元素
在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。分片是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个分片中存储不同类型的元素。
在Go的字节片中,你可以在 Join() 函数的帮助下连接字节片中的各个元素。或者换句话说,Join函数用来连接字节片中的元素,并返回一个新的字节片,其中包含所有这些由给定分隔符分隔的连接元素。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问Join函数。
语法
func Join(slice_1 [][]byte, sep []byte) []byte
这里,sep是放置在所产生的片断的元素之间的分隔符。让我们借助于例子来讨论这个概念。
例1 :
// Simple Go program to illustrate
// how to join a slice of bytes
package main
import (
"bytes"
"fmt"
)
// Main function
func main() {
// Creating and initializing
// slices of bytes
// Using shorthand declaration
name := [][]byte{[]byte("Sumit"),
[]byte("Kumar"),
[]byte("Singh")}
sep := []byte("-")
// displaying name of the student in parts
fmt.Printf("First Name: %s", name[0])
fmt.Printf("\nMiddle Name: %s", name[1])
fmt.Printf("\nLast Name: %s", name[2])
// Join the first, middle, and
// last name of the student
// Using Join function
full_name := bytes.Join(name, sep)
// Displaying the name of the student
fmt.Printf("\n\nFull name of the student: %s", full_name)
}
输出
First Name: Sumit
Middle Name: Kumar
Last Name: Singh
Full name of the student: Sumit-Kumar-Singh
例2 :
// Go program to illustrate how to
// join the slices of bytes
package main
import (
"bytes"
"fmt"
)
// Main function
func main() {
// Creating and initializing slices of bytes
// Using shorthand declaration
slice_1 := [][]byte{[]byte("Geeks"), []byte("for"), []byte("Geeks")}
slice_2 := [][]byte{[]byte("Hello"), []byte("My"),
[]byte("name"), []byte("is"), []byte("Bongo")}
// Displaying slices
fmt.Println("Slice(Before):")
fmt.Printf("Slice 1: %s ", slice_1)
fmt.Printf("\nSlice 2: %s", slice_2)
// Joining the elements of the slice
// Using Join function
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("+"))
// Displaying results
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)
}
输出
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
极客教程