如何在golang中正确地将map解包到自定义的嵌套结构中(aws sdk-for-go)

huangapple go评论92阅读模式
英文:

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

你正在在循环中分配keyval变量的地址,而实际上每个变量只有一个。你需要复制这些值,这样你才能为每个条目分配一个新的指针。最简单的方法是使用提供的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)
}

huangapple
  • 本文由 发表于 2017年1月27日 04:33:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41882463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定