doupinwan0563 2015-01-06 06:20
浏览 1534
已采纳

如何在golang中创建一个不固定的长度切片

Is there any way to create a unfixed length slice in go? As a example, I want to grab all the fileNames in a directory(content/) fill to a [] string slice.

The content/ dir contains:

$-> tree content/
content/
├── 1.txt
├── 2.txt
└── tmp

Here is what I currently got:

package main

import (
    "fmt"
    "io/ioutil"
)

func listFile() []string {
    list := make([]string, 100)
    // as you can see, I make a slice length as 100, but that is not appropriate.

    files, _ := ioutil.ReadDir("content")
    i := 0
    for _, f := range files{
        list[i] = f.Name()
        i = i+1
    }
    return list
}

func main(){
    fmt.Print(listFile())
}

What I want to achieve is a way to simulate the behavior of ArrayList in java, which I can just simply list.add() and wont care about the length.

Can slice in GoLang do that?

Thanks.

  • 写回答

3条回答 默认 最新

  • dorv56831 2015-01-06 06:39
    关注

    A Go slice can't do that, but the append() function will grow your slice in a matter that appending elements becomes an O(1) amortized operation:

    func listFile() []string {
        // make a slice of length 0
        list := make([]string, 0)
    
        files, _ := ioutil.ReadDir("content")
        for _, f := range files {
            // append grows list as needed
            list = append(list, f.Name())
        }
    
        return list
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决