我在main.tf中定义了列表嵌套属性规范,它看起来如下所示:

 di_name = [
    {
      source_name = "test1"
      new_d_name  = "test2"
      new_di_name = "test3"
      di_type     = "test4"
    },
    {
      source_name = "test1"
      new_d_name  = "test2"
      new_di_name = "test3"
      di_type     = "test4"
    },
  ]

它对应于以下内容.

"di_name" : schema.ListNestedAttribute{
                Optional: true,
                NestedObject: schema.NestedAttributeObject{
                    Attributes: map[string]schema.Attribute{
                        "source_name": schema.StringAttribute{
                            Required: true,
                        },
                        "new_d_name" : schema.StringAttribute{
                            Required: true,
                        },
                        "new_di_name" : schema.StringAttribute{
                            Required: true,
                        },
                        "di_type" : schema.StringAttribute{
                            Required: true,
                        },
                    },
                },







  type ModelStruct struct {

DName              []vmDi `tfsdk:"di_name"`
}

type vmDi struct {
    Source Name    types.String `tfsdk:"source_name"`
    NewDName       types.String `tfsdk:"new_d_name"`
    NewDiName      types.String `tfsdk:"new_di_name"`
    DiType         types.String `tfsdk:"di_type"`
}

在新的类/包希望是正确的在GO中,我有相应的 struct ,我想用数据初始化.

type VmBi struct {

  GetData [] VmDi
}


 type   VmDi struct {
        Source Name    string
        NewDName       string
        NewDiName      string
        DiType         string
    }

现在,我想使用这个Create方法从di_name列表中的main.tf获取所有值:

func (r *vmResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {

   Initialize struct with di_name values.
newData := newGoPackage.VmDi {


 Put data here from di_name

     }
    
  }

既然我不能在这里访问len(Di_Name),我该如何初始化该 struct 呢?

任何帮助都可以,先谢谢你.

推荐答案

我假设这是terraform-framework-plugin,因为用法看起来是一致的,尽管没有具体说明.要从资源模型初始化 struct ,必须声明该 struct ,然后使用请求中的State.Get将该 struct 修改为方法中的引用.然后,引用将包含来自Terraform配置的HCL2反序列化/未编组的值.通常还会将返回信息附加到响应诊断程序中.图案通常如下所示:

func (r *vmResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
  var state ModelStruct
  resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
  if resp.Diagnostics.HasError() {
      return
  }
  // state.DName now resolves as expected as type []vmDi and is iterable
}

Go相关问答推荐

Gorm foreign 密钥

如何复制*C.char?

CGO如何转换为文件*类型

切换选项卡时,Goland IDE中的光标自动转移

ChromeDriver不存在(高朗selenium)

如何修复 Go 中协议缓冲区定义中重新定义的字段?

如何忽略打印达到最大深度限制 go colly

linter 警告:返回值被忽略

如何在模板中传递和访问 struct 片段和 struct

整理时转换值

如何在时间范围内规范化数组的元素?

如何将一片十六进制字节转换为整数

将 []float64 像素切片转换为图像

vs 代码调试 go 测试不通过标志

httprouterhttp.HandlerFunc() 是如何工作的?

如何在循环中旋转图像以便在 golang 中创建 GIF?

是否可以使用按位运算在随机 unicode 字符串中找到重复字符?

如何从字符串中删除多个换行符`\n`但只保留一个?

行之间的模板交替设计

更改单个像素的 colored颜色 - Golang 图像