Home >Backend Development >Golang >How Do I Create and Resize Dynamic Arrays in Go?

How Do I Create and Resize Dynamic Arrays in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-26 08:24:10951browse

How Do I Create and Resize Dynamic Arrays in Go?

Resizable Arrays in Go

In Go, there are multiple approaches to creating dynamic arrays, which can be useful when working with data of variable size.

For instance, if you're comfortable with the std::vector class from C , you may wonder about its equivalent in Go. To achieve similar functionality, you can utilize the append() built-in function.

Here's an example that demonstrates how to create a dynamic array of structs:

type myType struct {
    a, b int
}

func main() {
    a := []myType{{1, 2}, {3, 4}}
    a = append(a, myType{5, 6})
}

By utilizing append(), you can dynamically extend the array by adding elements at the end. Here's a brief explanation of the code:

  • []myType declares a dynamic array of myType structs.
  • a := []myType{{1, 2}, {3, 4}} initializes the array with two elements.
  • a = append(a, myType{5, 6}) appends a new element to the end of the array.

For further details on append() and dynamic arrays, you can refer to the Go language specification.

The above is the detailed content of How Do I Create and Resize Dynamic Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn