更好的初始化

I am making an API call to AWS to get a list of AMIs using the Golang SDK. The DescribeImages function takes in DescribeImagesInput. I only want to see my own AMIs, so my code is doing this:

// Build input
self := "self"
ownerSelf := []*string{&self}
ownImages := &ec2.DescribeImagesInput{
    Owners: ownerSelf,
}

// Call the DescribeImages Operation
resp, err := svc.DescribeImages(ownImages)
if err != nil {
    panic(err)
}

Building input like that is very ugly. I am sure there is a better technique, but being a Golang n00b, I don't know it. What is a better way to do?

You can't get it any shorter than this:

self := "self"
ownImages := &ec2.DescribeImagesInput{Owners: []*string{&self}}

Or in one line (without the self string variable):

ownImages := &ec2.DescribeImagesInput{Owners: []*string{&[]string{"self"}[0]}}

(What happens here is I create a []string slice with one element "self", index its only element and take its address and use this value to initialize the required []*string.)

What you can do is create a helper function which constructs the slice of string pointers for you:

func sp(es ...string) []*string {
    s := make([]*string, len(es))
    for i := range es {
        s[i] = &es[i]
    }
    return s
}

With this, the delcaration becomes:

ownImages = &ec2.DescribeImagesInput{Owners: sp("self")}

Try it on the Go Playground.

I don't know how much more acceptable this is, but it should do the same:

self := "self"
resp, err := svc.DescribeImages(
    &ec2.DescribeImagesInput{
        Owners: []*string{&self},
    },
}
if err != nil {
    panic(err)
}

Which could of course be shortened, albeit at the cost of readability IMO

self := "self"
resp, err := svc.DescribeImages(&ec2.DescribeImagesInput{Owners:[]*string{&self}}}
if err != nil {
    panic(err)
}