Why are struct literals "literal"
Asked Answered
P

2

16

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?

Pithos answered 20/3, 2015 at 18:44 Comment(3)
You might expect it to, but literal generally doesn't imply constant. This is the case in a lot of languages.Isochroous
so what does it mean? lolPithos
because they are literals? :DVulture
B
29

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:

Builtup answered 20/3, 2015 at 19:4 Comment(3)
Other examples: 1 is an int literal, "foo" is a string literal, etc.Spline
An easy way to remember this is that the data for the struct is literally right there in the code.Fuchs
It means it's not constructed by creating an empty one and adding or subtracting as you go. Made it super clear for me. Thank you @andyfeller 🙌🏼Luxembourg
P
0

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 }
Psyche answered 29/1, 2023 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.