slice
Publish on 2024-09-19

How to copy or duplicate a slice in Go

Using `copy()`

When using the copy function, there one major thing to note: the lengths of both destination and source slices do not have to be equal. It will only copy up to the smaller number of elements. So if you attempt to copy to an empty or nil slice, nothing will be copied.

func main() {
	s1 := []int{1, 2, 3, 4, 5}
	s2 := make([]int, len(s1))

	copy(s2, s1)
	fmt.Println(s1, s2) // [1 2 3 4 5] [1 2 3 4 5]

	s2[1] = 10 // changing s2 does not affect s1
	fmt.Println(s1, s2) // [1 2 3 4 5] [1 10 3 4 5]
}
Using `append()`
func main() {
	s1 := []int{1, 2, 3, 4, 5}
	s2 := []int{}
	s2 = append([]int(nil), s1...)

	fmt.Println(s1, s2) // [1 2 3 4 5] [1 2 3 4 5]

	s1[0] = 20
	fmt.Println(s1, s2) // [20 2 3 4 5] [1 2 3 4 5]
}
Edge case 1. `copy()` related
func main() {
	var s1 []int
	s2 := make([]int, len(s1))

	copy(s2, s1)
	fmt.Println(s1 == nil, s2 == nil) // true false
}

u need to know what make() do.

func main() {
	var s1 []int
	s2 := make([]int, len(s1))

	if s1 == nil {
		s2 = nil
	} else {
		copy(s2, s1)
	}

	fmt.Println(s1 == nil, s2 == nil) // true true
}
  1. append() related
func main() {
	s1 := make([]int, 0)
	var s2 []int
	s2 = append([]int(nil), s1...)

	fmt.Println(s1 == nil, s2 == nil) // false true
}

what if it’s append?

func main() {
	s1 := make([]int, 0)
	var s2 []int
	s2 = append(s1[:0:0], s1...)

	fmt.Println(s1 == nil, s2 == nil) // false false
}
© 2024 humbornjo :: based on 
nobloger  ::  rss