The built-in copy function copies the source element into the destination element and returns the destination element length.
func Copy( dst , src [] Type) int
There are some special case using this function which is we can copy a string into an byte slice variable func Copy( dst []byte, src string) int
Examples:
package main import "fmt" func main() { var arr = make([]string, 2) n := copy(arr, []string{"hi", "hello", "welcome", "ll"}) fmt.Println("element length :", n) fmt.Println("values :", arr) }
Output:
element length : 2 values : [hi hello]
Special Case example:
package main import "fmt" func main() { var b = make([]byte, 5) // copy from a string to byte slice n := copy(b, "vicky") fmt.Println("element length :", n) fmt.Println("values :", string(b)) }
Output:
element length : 5 values : vicky
Comments
Post a Comment