英文:
How to properly unpack a map into a custom nested struct in golang(aws sdk-for-go)
问题
我有一个包含两个值(Etag和PartNumber)的地图,如下所示:
upload_out := make(map[int64]string) //key - PartNumber, value - Etag
我最终想要遍历这个地图,并将它们转储到一个自定义结构的切片中,如下所示:
Parts: []*s3.CompletedPart{
{ // Required
ETag: aws.String("ETag1"),
PartNumber: aws.Int64(PartNumber1),
},
{ // Required
ETag: aws.String("ETag2"),
PartNumber: aws.Int64(PartNumber2),
},
// 更多的值...
},
我猜我的问题是不知道如何正确地做到这一点。我的尝试循环只会一次添加一个键值对。因此,并没有解包所有的值。
var paths []*s3.CompletedPart
for key, val := range upload_out {
//var unique [10000]*s3.CompletedPart //Attempt unique variable names
name := &s3.CompletedPart{ // this only does one
ETag: &val,
PartNumber: &key,
}
paths = append(paths, name)
}
希望能帮到你。
英文:
I have a map that contains two values (Etag & PartNumber) as follows:
upload_out := make(map[int64]string) //key - PartNumber, value - Etag
i eventually want to loop through this map with my values and dump them into into a slice of custom struct as follows:
Parts: []*s3.CompletedPart{
{ // Required
ETag: aws.String("ETag1"),
PartNumber: aws.Int64(PartNumber1),
},
{ // Required
ETag: aws.String("ETag2"),
PartNumber: aws.Int64(PartNumber2),
},
// More values...
},
I guess my problem is not understanding how to properly do this. My attempt loop below only adds one key, value pair all the time. So not all values are being unpacked.
var paths []*s3.CompletedPart
for key, val := range upload_out {
//var unique [10000]*s3.CompletedPart //Attempt unique variable names
name := &s3.CompletedPart{ // this only does one
ETag: &val,
PartNumber: &key,
}
paths = append(paths, name)
}
Any help doing this right will be appreciated.
答案1
得分: 1
你正在在循环中分配key
和val
变量的地址,而实际上每个变量只有一个。你需要复制这些值,这样你才能为每个条目分配一个新的指针。最简单的方法是使用提供的aws便利函数:
for key, val := range upload_out {
name := &s3.CompletedPart{
ETag: aws.String(val),
PartNumber: aws.Int64(key),
}
paths = append(paths, name)
}
英文:
You are assigning the address of the key
and val
variables in your loop, which there is only ever one of each. You need to copy those values so you can assign a new pointer for each entry. The easiest way is to use the provided aws convenience functions:
for key, val := range upload_out {
name := &s3.CompletedPart{
ETag: aws.String(val),
PartNumber: aws.Int64(key),
}
paths = append(paths, name)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论