Standard library / slices

slices.Clone()

Makes a shallow copy of the slice elements. Preserves nil; nested reference values can still share state. Expected stdout: '[1 2] [9 2]\n'.

Formal Syntax & Structure

go syntaxgo
func Clone[S ~[]E, E any](s S) S

Parameters & Attributes

NameTypeDescription
sSInput slice; may share its backing array.

Return Value

S

Makes a shallow copy of the slice elements. Preserves nil; nested reference values can still share state.

Working Example

Example Snippetgo
package main
import (  "fmt"  "slices")
func main() {  a := []int{1, 2}  b := slices.Clone(a)  b[0] = 9  fmt.Println(a, b)}
Go Reference