Logo

Programming-Idioms

# 227 Copy a list
Create the new list y containing the same elements as the list x.

Subsequent modifications of y must not affect x (except for the contents referenced by the elements themselves if they contain pointers).
Implementation
Go

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Go implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
y := make([]T, len(x))
copy(y, x)
let y = x.slice();
uses classes;
y.assign(x);
y = x.dup
List<T> y = x.ToList();
List<Int32> y = new List<Int32>(x);
y = x[:]
let y = x.clone();
type (foo), allocatable, dimension(:) :: y
y = x
use Storable qw(dclone);
my @y = @x; # for simple arrays

# for complex arrays with references:
my @y = @{dclone(\@x)};
y = [...x];
import java.util.ArrayList;
ArrayList<String> y = new ArrayList<>(x);
y = x.copy()
local function deepcopy(input)
 local t=type(input)
 if t~="table" then
  return input
 end
 local copy={}
 for k,v in pairs(input) do
  k=deepcopy(k)
  v=deepcopy(v)
  copy[k]=v
 end
 return copy
end
local y=deepcopy(x)