Anonymous Structure and Field in Golang
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct.
Anonymous Structure
In Go language, you are allowed to create an anonymous structure. An anonymous structure is a structure which does not contain a name. It useful when you want to create a one-time usable structure. You can create an anonymous structure using the following syntax:
variable_name := struct{
// fields
}{// Field_values}
Let us discuss this concept with the help of an example:
Example:
package main
import "fmt"
func main() {
Element := struct {
name string
branch string
language string
Particles int
}{
name: "Pikachu" ,
branch: "ECE" ,
language: "C++" ,
Particles: 498,
}
fmt.Println(Element)
}
|
Output:
{Pikachu ECE C++ 498}
Anonymous Fields
In a Go structure, you are allowed to create anonymous fields. Anonymous fields are those fields which do not contain any name you just simply mention the type of the fields and Go will automatically use the type as the name of the field. You can create anonymous fields of the structure using the following syntax:
type struct_name struct{
int
bool
float64
}
Important Points:
In a structure, you are not allowed to create two or more fields of the same type as shown below:
type student struct{
int
int
}
If you try to do so, then the compiler will give an error.
You are allowed to combine the anonymous fields with the named fields as shown below:
type student struct{
name int
price int
string
}
Let us discuss the anonymous field concept with the help of an example:
Example:
package main
import "fmt"
type student struct {
int
string
float64
}
func main() {
value := student{123, "Bud" , 8900.23}
fmt.Println( "Enrollment number : " , value. int )
fmt.Println( "Student name : " , value.string)
fmt.Println( "Package price : " , value.float64)
}
|
Output:
Enrollment number : 123
Student name : Bud
Package price : 8900.23
Last Updated :
12 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...