In golang what are struct literals?
Why is the following a literal even though there is a variable? And aren't structs literally variable, even when not const? So how does it make sense.
MyType{Field: var)
It has a variable and yet it's a "literal"?
Also why is it only called a "struct literal" when you first initialize it?
Programming languages use the word "Literal" when referring to syntactic ways to construct some data structure. It means it's not constructed by creating an empty one and adding or subtracting as you go.
Compare:
MyType{Field: myVariable}
to
var x = new(MyType)
x.Field = myVariable
The benefit is that your code's appearance reflects the data structure in some way. The downside is that you have to know the layout in advance and have the content initialized already, not possible, if for instance, you're constructing a map with unknown keys.
Here are links to the literals in the Go language specification. Notice that they all are syntactic ways to define a data structure:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With