duanou2526 2014-09-16 11:03
浏览 24
已采纳

有没有更好的方法来处理可变大小的切片?

please see the code below

names := make([]string, 0, 100)
names = append(names, "Jack")
names = append(names, "Jacob")
// adding many names in here

Given a circumstances like this: I will get these names from somewhere else, before that I didn't know the size of it. So I a need a dynamic array to contains these names. The above code is way that I came up with. I was wonder if there is any more elegant way to do this.

If I initialise like this

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.

I suppose this would be a such waste on memory. I am totally new to static programming language, so if there is any wrong concept in this post, please point it out.

  • 写回答

3条回答 默认 最新

  • dongwu9972 2014-09-16 11:11
    关注

    Just only declare the type and then assign the appended slice to it:

    package main
    
    import "fmt"
    
    func main() {
        var names []string
        names = append(names, "foo")
        names = append(names, "bar")
        fmt.Println(names)
    }
    

    Yields:

    >> [foo bar]
    

    If you are into the mechanics of it, here is a nice blog post.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数