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.

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


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

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

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

Output: "aaaa"

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

Output: {10, 20, 10, 20}

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

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


package main

import (

// 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))



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


Posted in bytes, golang, packages

Leave a Reply

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