如何在Go中实现可调整大小的数组 [英] How to implement resizable arrays in Go

查看:123
本文介绍了如何在Go中实现可调整大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C ++背景,我习惯于使用 std :: vector 类来实现这样的事情。
假设我想要一个这样的动态数组:

 键入一个struct {
b int
c string
}

这么做的标准方法是什么?



一段代码会非常有用 使用 append()内置



示例:

  type mytype struct {
a,b int
}

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

有关追加的更多信息,请参阅规范

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

解决方案

Use the append() builtin

Example:

type mytype struct {
  a, b int
}

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

Refer to the spec for more info on append.

这篇关于如何在Go中实现可调整大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆