Golang copy() Function with Examples

Golang | copy() Function: Here, we are going to learn about the built-in copy() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 14, 2021 [Last updated : March 15, 2023]

copy() Function

In the Go programming language, the copy() is a built-in function that is used to copy the elements from a source slice into a destination slice and returns the number of copied elements copied.

It accepts two parameters (dst, src []Type) and returns the number of copied elements.

Syntax

func copy(dst, src []Type) int

Parameter(s)

  • dst : The destination slice in which we have to copy the elements.
  • src : The source slice whose elements are to be copied.

Return Value

The return type of the copy() function is an int, it returns the total number of copied elements.

Example 1

// Golang program to demonstrate the
// example of copy() function

package main

import (
	"fmt"
)

func main() {
	// Creating int and string slices
	s1 := []int{10, 20, 30}
	s2 := []string{"Hello", "World"}

	s3 := make([]int, len(s1))
	s4 := make([]string, len(s2))

	// Printing types and values of slices
	fmt.Printf("s1: %T, %v\n", s1, s1)
	fmt.Printf("s2: %T, %q\n", s2, s2)

	// Copying slices
	m := copy(s3, s1)
	fmt.Println(m, "elements copied.")

	n := copy(s4, s2)
	fmt.Println(n, "elements copied.")

	// After copying,
	// Printing types and values of slices
	fmt.Println("After copying...")
	fmt.Printf("s3: %T, %v\n", s3, s3)
	fmt.Printf("s4: %T, %q\n", s4, s4)
}

Output

s1: []int, [10 20 30]
s2: []string, ["Hello" "World"]
3 elements copied.
2 elements copied.
After copying...
s3: []int, [10 20 30]
s4: []string, ["Hello" "World"]

Example 2

// Golang program to demonstrate the
// example of copy() function

package main

import (
	"fmt"
)

func main() {
	// Creating a byte slice
	s := "Hello"
	b := make([]byte, len(s))

	// Printing types and values
	fmt.Printf("s: %T, %q\n", s, s)
	fmt.Printf("b: %T, %q\n", b, b)

	// Copying bytes from a string
	// to a slice of bytes
	n := copy(b, s)
	fmt.Println(n, "elements copied.")

	// After appending,
	// Printing type and value of slice
	fmt.Println("After copying...")
	fmt.Printf("s: %T, %q\n", s, s)
	fmt.Printf("b: %T, %q\n", b, b)
}

Output

s: string, "Hello"
b: []uint8, "\x00\x00\x00\x00\x00"
5 elements copied.
After copying...
s: string, "Hello"
b: []uint8, "Hello"

Golang builtin Package »






Comments and Discussions!

Load comments ↻






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