nhooyr
nhooyr

Reputation: 1204

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?

Upvotes: 16

Views: 13149

Answers (2)

Izana
Izana

Reputation: 3105

literal just means the grammar or the way to compose source code, i.e., construct a value of a certain type following the literal meaning of its source code.

int/string literal happens to construct a constant value that is the same as the literal meaning of the source code.

from go spec

Composite literals construct new composite values each time they are evaluated.

from their definition, it's syntactic sugar to construct value for the composite type. It's not the fixed value referred by literal wiki page.

cited from gopl 4.4.1 for struct literal:

A value of a struct type can be written using a struct literal that specifies values for its fields.

type Point struct{ X, Y int }
p := Point{1, 2}

Both string literals and struct literals are source codes to guide the compiler to construct value in memory. struct literals can be non-constant at compile time, i.e., only known at runtime.

there's also another type of literal: type literal:

A type may also be specified using a type literal, which composes a type from existing types.

which just means a fixed value in the source code for the type system.

struct{}
struct{ foo int32 }

Upvotes: 0

Chris Pfohl
Chris Pfohl

Reputation: 19044

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:

Upvotes: 30

Related Questions