I'm new to Go and have two questions about types.
For example, take this code:
type Rule struct {
handler func() (err error)
creator string
args struct {
extension string
action string
folder struct {
location string
storage string
}
}
}
1) How can I create a new Rule
using a single literal declaration and assign values to the properties of args
? What is wrong with this code:
rule := Rule{
args: {
extension: "png,jpg,gif,svg",
action: "move",
},
}
2) Is it possible to define types within types? For instance, without breaking the code into two separate type declarations, could I modify the args
portion of the Rule
type so that it defines a second type called RuleArgs
?
I know that I can break these out into multiple assignments and declarations, but my question is do I have to (ie. does Go make it impossible not to)?
Nested structs are a thing in go, but they can induce some messiness. To instantiate the given object, try this:
type Rule struct {
handler func() (err error)
creator string
args struct {
extension string
action string
}
}
rule := Rule{
args: struct {
extension string
action string
}{
extension: "png,jpg,gif,svg",
action: "move",
},
}
Notice that I have the structure's argument names and types listed. Also note I removed the folder
argument for brevity.
If you want to do it in multiple lines:
rule2 := Rule{}
rule2.args.action = "some-action"