乐闻世界logo
搜索文章和话题

How to Create Slices in Golang?

2月7日 13:23

In Go, creating slices can be achieved through the following methods:

  1. Using the built-in make function:

    go
    s := make([]int, 10) // Creates a slice with length and capacity of 10, element type int
  2. Using literals:

    go
    s := []int{1, 2, 3} // Creates a slice initialized with three elements: 1, 2, 3
  3. By using an existing array or slice:

    go
    arr := [5]int{1, 2, 3, 4, 5} s := arr[1:4] // Creates a new slice referencing elements from index 1 to 3 (excluding index 4) in the array

These methods provide flexible ways to create and initialize slices.

标签:Golang