Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are struct literals "literal"

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?

like image 533
nhooyr Avatar asked Mar 20 '15 18:03

nhooyr


1 Answers

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:

  • Lexical elements
    • Integer literals
    • Floating-point literals
    • Imaginary literals
    • Rune literals
    • String literals
  • Expressions
    • Composite literals
    • Function literals
like image 126
Chris Pfohl Avatar answered Oct 23 '22 10:10

Chris Pfohl