-1

I'm studying slices in golang and i learn how to initialize slices in two different ways:

func main() {
    slice1 := make([]int, 5, 10)
    slice1 = append(slice1, 1, 2, 3, 4)

    slice2 := []int{1, 2, 3, 4}
}

what is the difference?

I'm search and found nothing about it, if someone can answer I'll be glad.

1 Answers1

1

The following creates a slice with length 5 and capacity 10 (i.e. allocates an array with 10 elements, creates a slice pointing to that array, with length=5). This happens at runtime, and the slice elements are initialized to zero values:

slice1 := make([]int, 5, 10)

The following creates a slice with length=4 and capacity=4

slice2 := []int{1, 2, 3, 4}

The array literal []int{1,2,3,4} is created at compile time, and the slice is created at runtime pointing to the array with len=4 and cap=4.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59