【问题标题】:Same file name on iterating ListObject迭代 ListObject 时文件名相同
【发布时间】:2021-03-26 14:55:41
【问题描述】:

我想读取 minio 存储中存储桶中的文件列表。按照文档,我执行以下步骤:

var listFile []*string
minioClient, err := minio.New(location, user, password, true)
// Create a done channel.
doneCh := make(chan struct{})
defer close(doneCh)
// Recursively list all objects in 'mytestbucket'
recursive := true
bucket := "private"
url := "production/font/"
objectCh := minioClient.ListObjects(bucket, url, recursive, doneCh)
for message := range objectCh {
    listFile = append(listFile, &message.Key)
}
return listFile, err

当我读取文件列表时,我将获得一个包含 24 个项目但文件名相同的数组,例如:

"production/font/merriweathersans-regular-webfont.ttf",
"production/font/merriweathersans-regular-webfont.ttf",
"production/font/merriweathersans-regular-webfont.ttf",
"production/font/merriweathersans-regular-webfont.ttf",
"production/font/merriweathersans-regular-webfont.ttf",
...

但我应该看到该目录的所有文件名:

"production/font/Nexa-Light.ttf",
"production/font/Nexa-Bold.ttf",
"production/font/merriweathersans-regular-webfont.ttf",
....

我哪里错了?

【问题讨论】:

  • for range 循环重用它们的迭代变量,即message 变量代表单个存储位置,并且该位置在下一次迭代时不会改变,只有数据在它的变化。因此,在每次迭代中,当您获取该位置的地址 (&message.Key) 时,您始终会获得相同的地址,因此 listFile 切片包含每个指向该单个位置的指针。您需要复制迭代变量,然后您可以获取该变量的地址。例如message := message 然后listFile = append(listFile, &message.Key)

标签: go minio


【解决方案1】:

问题是循环中的一个错字,即将&message.Key 附加到listFile。这里message 变量始终是相同的,并且您正在附加相同的变量,因此listFile 始终指向message.key 的最后一个值。

要解决此问题,您可以:

for message := range objectCh {
    tmpMessage := message
    listFile = append(listFile, &tmpMessage.Key)
}

【讨论】:

  • 这是一个通道上的range,而不是切片或数组,所以no idx 那里,只有值。
  • @mkopriva 哦,我没注意到,谢谢。我更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 2022-07-11
  • 1970-01-01
  • 2017-02-28
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多