【发布时间】: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)。