How to implement resizable arrays in Go

前端 未结 6 1822
遥遥无期
遥遥无期 2020-12-08 08:57

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:

typ         


        
6条回答
  •  轮回少年
    2020-12-08 09:32

    you might also be able to make do with a slice. which is an array that knows its current length. And can have a separate current length and maximum capacity. Note the values passed for initial size and capacity do not have to be constants so you can create a function which builds and returns slices of different lengths based on its parameters.

    The up side is that a slice []Int can just be indexed like an array, and will return ints when used in this way.

    The downside is that it will not automatically grow byound its stated capacity. Effective Go has an example of how you would go about handling reallocation.

    the code would be

    type mytype struct {
       a, b int
    }
    
    
    
    
    func main() {
    
      sl := make([]mytype, 10, 50) //slice of 10 items, max capacity 50 these do not have to be constant expressions.
      sl[0] = mytype{1,2}
       //...
      for i, value := range sl {
      // ... do stuff with value
      }
    }
    

提交回复
热议问题