Edwinner
Edwinner

Reputation: 2657

How to properly unpack a map into a custom nested struct in golang(aws sdk-for-go)

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.

Upvotes: 0

Views: 418

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109417

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)
}

Upvotes: 1

Related Questions