Home >Backend Development >Golang >How Do I Implement Resizable Arrays in Go?

How Do I Implement Resizable Arrays in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 00:02:00648browse

How Do I Implement Resizable Arrays in Go?

Implementing Resizable Arrays in Go

As a C developer transitioning to Go, you may be accustomed to using the std::vector class for dynamic arrays. In Go, a similar functionality can be achieved with an appendable slice data structure.

Standard Approach

To create a dynamic array of structs, you can define the struct type and then use slices to store instances of the struct. Slices are dynamically sized, allowing you to add or remove elements at runtime.

Example Code Snippet

type myStruct struct {
    b int
    c string
}

func main() {
    // Create an empty slice of myStruct
    a := []myStruct{}

    // Append elements to the slice
    a = append(a, myStruct{1, "hello"})
    a = append(a, myStruct{2, "world"})

    // Iterate over and print the slice
    for _, v := range a {
        fmt.Println(v)
    }
}

Key Function: append()

The append() function is central to working with slices in Go. It takes a slice as its first argument and one or more elements as its remaining arguments. It appends the specified elements to the slice and returns a new slice with the appended elements.

Further Reading

For more detailed information on slices and the append() function, refer to the Go specification: https://go.dev/ref/spec#Appending_and_copying_slices

The above is the detailed content of How Do I Implement Resizable 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