我有一个正在填充的 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 ; for image := range images {
file = imageFiles[image]
if len(file) == 0 {
// do something here
continue
}
print file[0].Name
}
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/