Golang bytes.Repeat() Function with Examples

Golang | bytes.Repeat() Function: Here, we are going to learn about the Repeat() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 25, 2021

bytes.Repeat()

The Repeat() function is an inbuilt function of the bytes package which is used to get a new byte slice consisting of count copies of the byte slice (b).

It accepts two parameters (b []byte, count int) and returns a new byte slice consisting of count copies of b.

Note:

  • The bytes.Repeat() function may create panic if count is negative or if the result of (len(b) * count) overflows.

Syntax:

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

Parameter(s):

  • b : The byte slice whose copies are to be created.
  • count : The value of count.

Return Value:

The return type of the bytes.Repeat() function is a []byte, it returns a new byte slice consisting of count copies of b.

Example 1:

// Golang program to demonstrate the
// example of bytes.Repeat() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Printf("%s\n",
		bytes.Repeat([]byte("Hello! "), 2))
	fmt.Printf("%s\n",
		bytes.Repeat([]byte("A"), 10))
	fmt.Printf("%s\n",
		bytes.Repeat([]byte("Alex"), 0))
}

Output:

Hello! Hello! 
AAAAAAAAAA

Example 2:

// Golang program to demonstrate the
// example of bytes.Repeat() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var result []byte
	var n int

	str = "Hello, world "
	n = 5
	result = bytes.Repeat([]byte(str), n)
	fmt.Printf("%s\n", result)

	str = "Yes!"
	n = 3
	result = bytes.Repeat([]byte(str), n)
	fmt.Printf("%s\n", result)

	str = "Okay!"
	n = 0
	result = bytes.Repeat([]byte(str), n)
	fmt.Printf("%s\n", result)
}

Output:

Hello, world Hello, world Hello, world Hello, world Hello, world 
Yes!Yes!Yes!

Golang bytes Package »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.