Anonymous Structure in Golang
An Anonymous structure in Golang is a structure which does not have any name in its definition. As the Anonymous structure does not have any name, it can’t be referenced elsewhere in the program. It is a one-time usable structure.
Syntax
The syntax of the Anonymous structure in Golang is given below:

Example
The example is shown below:
package main
import "fmt"
// main function
func main() {
// creating the anonymous structure named Element
Element := struct {
name string
age int
Dept string
Year int
}{
// initializing the anonymous structure
name: "xyz",
age: 20,
Dept: "IT",
Year: 2023,
}
// displaying the anonymous structure
fmt.Println(Element)
}
Output

Anonymous Fields in Golang
Like the Anonymous structure in Golang, a field in a structure can’t have any name. These are known as the Anonymous fields.
In this case, the type will become the field name.
Syntax
The syntax of the Anonymous fields is given below:

Example
package main
import "fmt"
type student struct{
name string
id int
dept string
string
}
// main function
func main() {
// Assigning values to the anonymous field and named fileds
value := student{"xyz" , 111, "CST", "2022"}
fmt.Println("Name: " , value.name)
fmt.Println("Id: ", value.id)
fmt.Println("Dept: ", value.dept)
fmt.Println("Passout: ", value.string) // accessing the anonymous filed using the type name
}
Output

Frequently Asked Questions
What is a structure?
A structure is a user-defined type which allows you to combine a group of elements, possibly of different types, into a single type.
What do you mean by the Anonymous structure?
An Anonymous structure in Golang is a structure which does not have any name in its definition.
When should I use the Anonymous structure?
As the Anonymous structure does not contain any name, it can’t be referenced elsewhere in the program, thus for the cases when the structure is meant to use only once.
What do you mean by the Anonymous field?
If a field in a structure does not contain any name, it is known as the Anonymous field.
Conclusion
In this article, we have extensively discussed Anonymous Structure and Fields in Go.
We started with the basic introduction, then we discussed,
- About the Structure in Golang
- Anonymous Structure in Go
-
Anonymous Fields in Go
You can also consider our Online Coding Courses such as the DSA in Python, C++ DSA Course, DSA in Java Course to give your career an edge over others.
Happy Reading!