duanjiao8007 2015-03-31 03:26 采纳率: 100%
浏览 26
已采纳

更好的初始化

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?

  • 写回答

2条回答 默认 最新

  • dttnb997315 2015-03-31 06:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题