Golang 如何重复一个字节的片断

Golang 如何重复一个字节的片断

在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。分片是一个可变长度的序列,用来存储相似类型的元素,你不允许在同一个片中存储不同类型的元素。

在Go的字节片中,你可以在Repeat()函数的帮助下将片中的元素重复到一个特定的次数。这个方法返回一个新的字符串,其中包含了片断中的重复元素。它被定义在字节包中,所以你必须在你的程序中导入字节包以访问Repeat函数。

语法

func Repeat(slice_1 []byte, count int) []byte
Go

这里,slice_1代表字节的片断,count值代表你想重复给定slice_1的元素多少次。

例子

// Go program to illustrate how to repeat
// the elements of the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
// Main function
func main() {
  
    // Creating and initializing
    // the slice of bytes
    // Using shorthand declaration
    slice_1 := []byte{'G', 'E', 'E', 'K', 'S'}
    slice_2 := []byte{'A', 'P', 'P', 'L', 'E'}
  
    // Repeating the given slice
    // Using Repeat function
    res1 := bytes.Repeat(slice_1, 2)
    res2 := bytes.Repeat(slice_2, 4)
    res3 := bytes.Repeat([]byte("Geeks"), 5)
  
    // Display the results
    fmt.Printf("Result 1: %s", res1)
    fmt.Printf("\nResult 2: %s", res2)
    fmt.Printf("\nResult 3: %s", res3)
}
Go

输出

Result 1: GEEKSGEEKS
Result 2: APPLEAPPLEAPPLEAPPLE
Result 3: GeeksGeeksGeeksGeeksGeeks
Go

注意: 如果count的值是负的,或者( len(slice_1) * count )的结果溢出,这个方法就会发生恐慌。

例子

// Go program to illustrate how to repeat
// the elements of the slice of bytes
package main
  
import (
    "bytes"
    "fmt"
)
  
// Main function
func main() {
  
    // Creating and initializing 
    // the slice of bytes
    // Using shorthand declaration
    slice_1 := []byte{'G', 'E', 'E', 'K', 'S'}
    slice_2 := []byte{'A', 'P', 'P', 'L', 'E'}
  
    // Repeating the given slice
    // Using Repeat function
    // If we use a negative 
    // value in the count
    // then this function will 
    // panic because negative
    // values are not allowed to count
    res1 := bytes.Repeat(slice_1, -2)
    res2 := bytes.Repeat(slice_2, -4)
    res3 := bytes.Repeat([]byte("Geeks"), -5)
  
    // Display the results
    fmt.Printf("Result 1: %s", res1)
    fmt.Printf("\nResult 2: %s", res2)
    fmt.Printf("\nResult 3: %s", res3)
}
Go

输出

panic: bytes: negative Repeat count

goroutine 1 [running]:
bytes.Repeat(0x41a787, 0x5, 0x5, 0xfffffffe, 0x66ec0, 0x3f37, 0xf0a40, 0x40a0d0)
/usr/local/go/src/bytes/bytes.go:485 +0x1a0
main.main()
/tmp/sandbox192154574/prog.go:22 +0x80
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册