What is the bytes.Clone() Function in Golang

The bytes.Clone() is a new function added in Go 1.20 that “returns a copy of a byte slice with a new backing array.” It is similar to copy() or make() functions but more convenient.


func Clone(b []byte) []byte


byte: It takes a byte slice as a parameter.

Return value

It returns a copy of b[:len(b).


package main

import (

func main() {
  // Create a byte slice
  b := []byte("Hello, world!")
  fmt.Println("Original:", string(b))

  // Clone the byte slice
  c := bytes.Clone(b)
  fmt.Println("Clone:", string(c))

  // Modify the original byte slice
  b[0] = 'h'
  fmt.Println("Modified original:", string(b))

  // The clone is not affected
  fmt.Println("Clone:", string(c))


Original: Hello, world!
Clone: Hello, world!
Modified original: hello, world!
Clone: Hello, world!

That’s it!

Related posts

Go bytes.Equal()

Go bytes.Compare()

Leave a Comment