![]() |
VOOZH | about |
In Golang, structures (or structs) allow us to group elements of various types into a single unit, which is useful for modeling real-world entities. Anonymous structures are unnamed, temporary structures used for a one-time purpose, while anonymous fields allow embedding fields without names.
Example:
variable := struct { field1 dataType1 field2 dataType2 # Anonymous Structure
// Additional fields as needed}{value1, value2}type StructName struct { dataType1 dataType2 # Anonymous Fields // Additional anonymous fields}Table of Content
An anonymous structure in Go is defined without a name and is useful for creating a one-time, temporary structure. Here’s the syntax and a code example.
variable := struct {
field1 dataType1
field2 dataType2
// Additional fields as needed
}{value1, value2}Example
Name: A Enrollment: 12345 GPA: 3.8
In this code, we define a Student structure with an anonymous personalDetails structure inside it, which stores name and enrollment. We then initialize student with values for these fields and print them out.
Anonymous fields in Go allow you to define fields without explicit names, only specifying their types. This is beneficial when fields naturally follow type names.
type StructName struct {
dataType1
dataType2
// Additional anonymous fields
}Example
Enrollment: 12345 Name: A GPA: 3.8
Here, the data types (int, string, float64) act as the field names, so accessing the values relies on the types.
1. Uniqueness Requirement: You cannot use two fields of the same type in a struct. For example:
type InvalidStudent struct {
int
int // Error: duplicate type
}2. Combining Named and Anonymous Fields: You can mix anonymous and named fields within a struct.
type Student struct {
id int // Named field
int // Anonymous field
}