hashicorp / hcl2

Former temporary home for experimental new version of HCL
https://github.com/hashicorp/hcl
Mozilla Public License 2.0
375 stars 64 forks source link

gohcl and optional attributes #24

Closed sigil66 closed 6 years ago

sigil66 commented 6 years ago

Given the tags documented here:

https://godoc.org/github.com/hashicorp/hcl2/gohcl

How does one deal with optional attributes?

jen20 commented 6 years ago

Looks to me like this is implemented but not documented as a valid tag attribute in Godoc.

nicholasjackson commented 6 years ago

There are two options one is to use the optional tag with value types like so...

type Action struct {
    Output         string `hcl:"output"`
    OutputProvider providers.Provider

    Template string `hcl:"template,optional"`
}
action {
  output = "abc"
}

The other is you can use reference types like...

type Action struct {
    Output         string `hcl:"output"`
    OutputProvider providers.Provider

    Template *string `hcl:"template"`
}
action {
  output = "abc"
}

In the instance of an optional value you will end up with a type which has the default empty value so "" in the case of string. If you want to check nil then you need to use the reference type.

How come I have never seen that doc file before (probably because I didn't look) will update the docs in the morning (https://github.com/hashicorp/hcl2/blob/master/gohcl/doc.go)

sigil66 commented 6 years ago

Perfect, thank you for the explanation!