How to implement resizable arrays in Go

Viewed 106226

I come from a C++ background and I'm used to using the std::vector class for things like this. Lets assume I want a dynamic array of these:

type a struct {
    b int
    c string
}

What is the standard way of doing this?

A snippet would be very useful

7 Answers

For a Simpler Example of the append() builtin

friends := []string{"Adam"}

friends = append(friends, "Rahul") // Add one friend or one string
        
friends = append(friends, "Angelica", "Rashi") // Add multiple friends or multiple strings

append() Documentation here

Hi we can simply do this in two ways

type mytype struct {
  a, b int
}

Just do like this

  1. Without append

__

a := []mytype{mytype{1, 2}, mytype{3, 4}, mytype{4, 5}}
  1. With append

__

a:=  append([]mytype{}, mytype{1, 2}, mytype{3, 4}, mytype{4, 5})

Add as much as you want. First one is an easy way to do this. Hope this will help you.

Related