Generics
Preserving defined slice types in generics
Returning the inferred slice type S preserves the caller defined type, unlike returning []E alone. An independent backing array can be created by copying elements, but referenced objects within those elements may still be shared. Example output: 'main.Names Ada Lin'.
Formal Syntax & Structure
go syntaxgo
func Clone[S ~[]E, E any](s S) SWorking Example
Example Snippetgo
package main
import "fmt"
type Names []string
func clone[S ~[]E, E any](s S) S { if s == nil { return nil } c := make(S, len(s)) copy(c, s) return c}func main() { s := Names{"Ada"} c := clone(s) c[0] = "Lin" fmt.Printf("%T %s %s\n", c, s[0], c[0])}