📌  相关文章
📜  Golang中如何加入字节切片的元素?

📅  最后修改于: 2021-10-25 02:07:03             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,您可以在Join()函数的帮助下连接字节切片的元素。或者换句话说,Join函数用于连接切片的元素并返回一个新的字节切片,其中包含由给定分隔符分隔的所有这些连接元素。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 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