A structure refers to a user-defined type that allows you to organize multiple but related elements in a unit. We can think of a structure as a blueprint that represent a real-world entity or an object.
For example, we can create a structure to represent a car. We can then spin specific models of a car from that object.
What is An Anonymous Struct?
An anonymous struct is a structure that does not have a name. This means that we cannot reference the structure elsewhere in the code. Anonymous structures allow you to define ephemeral structures for one-time use.
An example syntax to create an anonymous structure is as shown:
// fields
}{field_values}
Create Anonymous Struct
Consider the example below that illustrates how to create an anonymous struct.
import "fmt"
funcmain() {
// create anon struct
car := struct {
manufacturer, year, model string
mileage int
price float64
}{
manufacturer: "Toyota",
model: "Camry",
mileage: 200000,
year: "2018",
price: 24380.00,
}
// print anon struct
fmt.Println(car)
}
In the example above, we create an anonymous struct and create an instance of the struct immediately.
The above code should print the struct as:
Anonymous Fields
Go allows you to create anonymous fields. As the name suggests, these are struct fields that do not have a name.
The syntax is as shown:
int
string
bool
}
If you are creating anonymous fields, you cannot have more than one field of the same type. For example:
string
string
}
The above syntax should return an error.
Consider the example below to create a struct with anonymous fields.
import "fmt"
funcmain() {
type car struct {
string
int
float64
}
camray := car{"Toyota Camry", 200000, 24380.00}
// print values
fmt.Println("Model: ", camray.string)
fmt.Println("Mileage: ", camray.int)
fmt.Println("Price: ", camray.float64)
}
The above code should return:
Mileage: 200000
Price: 24380
Conclusion
This guide covers what anonymous structures are, how to create them in Go and how to implement anonymous fields in a Go structure.
Happy Coding!!