【问题标题】:Calling valiable name from another variable从另一个变量调用变量名
【发布时间】:2020-10-09 21:12:37
【问题描述】:

请帮助从另一个变量中调用该变量。

我有获取 EC2 实例并在“*ec2.Instance”变量中返回的脚本。

我可以从静态文本中打印信息,例如:

fmt.Println(instance.InstanceType) // t3.small

但我有所需字段的列表,例如并且不知道如何动态使用此列表中的名称:

fields := []string{"InstanceId", "InstanceType", "PrivateIpAddress"}
for i := range fields {
    fmt.Println(fields[i])
    fmt.Println(instance.fields[i]) // Not correct ... :(
}

【问题讨论】:

  • 恐怕我不知道你在问什么你不能“调用变量”。你调用函数。什么是“不正确的”(除了您试图访问未导出字段的事实)?你看到了什么错误?
  • 这个问题没有错。此人正在尝试访问结构中的一组属性。

标签: arrays go aws-sdk-go


【解决方案1】:

你需要在 go 中使用反射来做到这一点。

关键是您需要在运行时“分析”返回值,并从“反射”结构中按名称访问属性。反射基本上意味着在运行时分析对象。

package main

import (
    "fmt"
    "reflect"
)

type whatever struct {
    cat string
    dog string
    animals int
    something string

}

func main() {

    wantProps := []string{ "cat", "animals"}
    we := whatever{cat: "meow", animals: 22}
    r := reflect.ValueOf(we)
    for _, propName := range wantProps {
        prop := r.FieldByName(propName)
        fmt.Println(propName, prop)
    }
}

更多细节:

Golang dynamic access to a struct property

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多