Menu Close

Go – bytes.Repeat() function in go

Here, bytes.Repeat() function is used to create new byte slice consisting of count copies of byte slice in go.

Repeat() built-in function of bytes package creates new byte slice with n number of repetition of byte slice elements.

bytes.Repeat() function prototype:

func Repeat(b []byte, count int) []byte

Input parameters:
b: byte slice
count: Repeat number of elements in byte slice.

Return:
1) It returns a new byte slice consisting of count copies of b.
2) It panics if count is negative
3) if the result of len(b)*count/count != len(b), Then also It panics.
4) It returns empty byte slice If count is 0

Explanation:

1)
b := []byte("abcd")
count := 2

Output: "abcdabcd" , here "abcd" repeated twice.

2)
s = []byte("a")
count := 4

Output: "aaaa"

3)
s := []byte{10, 20}
count := 2

Output: {10, 20, 10, 20}

4)
s := []byte("abcd")
count := 0

Output:  ,empty byte slice i.e []byte{}

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("abcd")
    count := 2
	fmt.Printf("%q", bytes.Repeat(s, count))
	
	
    s = []byte("a")
    count = 4
	fmt.Printf("\n%q", bytes.Repeat(s, count))

    
    s = []byte("abcd")
    count = 0
	fmt.Printf("\n%q", bytes.Repeat(s, count))
    
}

Output:

"abcdabcd"
"aaaa"
""

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *