Home > Backend Development > Golang > How to Deep Copy a Slice in Go: Append vs. Copy?

How to Deep Copy a Slice in Go: Append vs. Copy?

Mary-Kate Olsen
Release: 2025-01-01 03:44:10
Original
669 people have browsed it

How to Deep Copy a Slice in Go: Append vs. Copy?

How to Deep Copy a Slice in Go Concis and Efficiently

In Go, copying slices requires consideration for creating a new backing array to prevent unintentional modifications to the original array. There are several concise and well-performing ways to achieve this.

One approach is to use the append function:

copy := append([]T{}, orig...)
Copy after login

where T is the element type of the original slice orig. However, an alternative solution exists using the built-in copy function:

cpy := make([]T, len(orig))
copy(cpy, orig)
Copy after login

The copy function is optimized for copying slices within the language. From the Go documentation:

"The copy built-in function copies elements from a source slice into a destination slice. ... Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst)."

Note:

It's important to remember that these solutions copy values in the slice. If the slice contains pointers or structs with pointer fields, those pointers will still point to the same values as the original slice.

Benchmark:

Testing the append and copy approaches reveals similar performance characteristics:

BenchmarkCopy     100000         24724 ns/op
BenchmarkAppend   100000         24967 ns/op
Copy after login

The benchmark results suggest that both methods are equally efficient for deep copying slices.

The above is the detailed content of How to Deep Copy a Slice in Go: Append vs. Copy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template