【发布时间】:2014-09-16 11:03:44
【问题描述】:
请看下面的代码
names := make([]string, 0, 100)
names = append(names, "Jack")
names = append(names, "Jacob")
// adding many names in here
考虑到这样的情况:我会从其他地方得到这些名字,在此之前我不知道它的大小。所以我需要一个动态数组来包含这些名称。上面的代码是我想出的方法。我想知道是否有更优雅的方式来做到这一点。
如果我这样初始化
names := make([]string, 100, 200)
// then I use append in here
// I would get first 100 elements as empty, the append start at index 101.
我想这会浪费很多内存。 我对静态编程语言完全陌生,所以如果这篇文章中有任何错误的概念,请指出。
【问题讨论】: