go - 如何将值重新分配为 map 输出的空值

标签 go

我有一个正在填充的 map imageFiles

var imageFiles map[Image][]*File
imageFiles = getImageFiles(data)
for image := range images {
    file = imageFiles[image]
    print file[0].Name
}
文件为空时出现此错误。文件= [](当我打印时)
panic: runtime error: index out of range [0] with length 0
文件是结构
type File struct {
    Name    string 
    Size     string 
    Title   string 
}
有没有办法确保我可以将一些默认值放入文件中(例如空字符串),以便可以避免这种情况?)

最佳答案

您将Image映射到指向File []*File的指针的一部分。 slice 的默认/空值为nil。当 slice 为零时,所有索引均“超出范围”。
您的选择是:

  • 修改getImageFiles以返回至少包含一项的 slice ;
  • 添加代码以检查 slice 的长度:
    for image := range images {
        file = imageFiles[image]
        if len(file) == 0 {
            // do something here
            continue
        }
        print file[0].Name
    }
    
  • 为文件 slice 创建一个新类型,以隐藏基础实现:
    type FileList []*File
    
    func (f FileList) FirstName() string {
        if f == nil || len(f) == 0 {
            return ""
        }
        return f[0].Name
    }
    
    var imageFiles map[Image]FileList
    imageFiles = getImageFiles(data)
    for image := range images {
        file = imageFiles[image]
        print file.FirstName()
    }
    
  • 关于go - 如何将值重新分配为 map 输出的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62616092/

    相关文章:

    go - 如何在 Go 中提供可选参数?

    Go 没有将完整的数据写入文本文件

    文件在 Go 中既存在又不存在?

    在我关闭连接或退出客户端应用程序之前,golang 连接不会写入

    google-app-engine - App Engine 上使用 Go 的 GORM Cloud SQL 连接

    installation - 在本地目录中安装包

    python - 如何从 GCP 中的 Cloud Functions 调用用 Go 编写的 Dataflow 作业

    eclipse - 如何将外部包添加到 Google App Engine 的 GoClipse 项目?

    gorp PreUpdate 方法更新非自愿列

    git - 包 : cannot download, http ://*. com/*/*.git 使用不安全的协议(protocol)