Sobes.tech
Junior — Middle

Is it possible to implement or use a dynamic array in the Go language, and how is it done?

sobes.tech AI

Answer from AI

In Go, slices are used to implement dynamic arrays. A slice is a structure that contains a pointer to an array, a length, and a capacity, and allows changing size dynamically.

Example of creating and using a dynamic array:

package main
import "fmt"

func main() {
    var s []int          // empty slice
    s = append(s, 1)     // add element
    s = append(s, 2, 3)  // add multiple elements
    fmt.Println(s)       // [1 2 3]

    // You can also create a slice with initial capacity
    s2 := make([]int, 0, 5) // length 0, capacity 5
    s2 = append(s2, 10, 20)
    fmt.Println(s2)      // [10 20]
}

Slices automatically expand when appending elements via append, and if necessary, a new larger array is allocated and data is copied.

Thus, for a dynamic array in Go, it is enough to use slices and the append function.

Is it possible to implement or use a dynamic array in… - sobes.tech