English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Functions & Methods

Golang Structs

Golang Slices & Arrays

Golang Strings(String)

Golang Pointers

Golang Interfaces

Golang Concurrency

Golang Exceptions(Error)

Golang Miscellaneous

Go Anonymous Struct and Field

Structures in Golang are user-defined types that allow us to create a set of different types of elements within a single unit. Any real entity with a set of attributes or fields can be represented as a structure.

Anonymous structure

In Go language, it is allowed to create anonymous structures. Anonymous structures are structures without names. They are very useful when you need to create a temporary structure. You can create an anonymous structure using the following syntax:

variable_name := struct{
// fields
}{// Field_values}

Let's use an example to discuss this concept:

//Concept of anonymous structure
package main 
  
import "fmt"
  
func main() { 
  
    // Create and initialize an anonymous structure
    Element := struct { 
        name      string 
        branch    string 
        language  string 
        Particles int
    }{ 
        name:      "Zhan San", 
        branch:    "Development Department", 
        language:  "C"++" 
        Particles: 498, 
    } 
  
    //Display anonymous structure
    fmt.Println(Element) 
}

Output:

{Zhan San Development Department C++ 498}

Anonymous fields

In Go structures, it is allowed to create anonymous fields. Anonymous fields are those that do not contain any names. You just need to mention the field type, and Go will automatically use the type as the field name. You can create anonymous fields in the structure using the following syntax:

type struct_name struct{
    int
    bool
    float64
}

Important Note:

  • In a structure, it is 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 this, the compiler will throw an error.

  • It is allowed to combine anonymous fields with named fields, as shown below:

    type student struct{
     name int
     price int
     string
    }
  • Let's use an example to discuss the concept of anonymous fields:

    package main 
      
    import "fmt"
      
    //Create an anonymous field in the structure 
    type student struct { 
        int
        string 
        float64 
    } 
      
    // Main function 
    func main() { 
      
        // Assign values to the fields of the anonymous, student structure
        value := student{123, "Bud", 8900.23} 
      
        fmt.Println("Number of Admissions: ", value.int) 
        fmt.Println("Student Name: ", value.string) 
        fmt.Println("Package Price: ", value.float)64) 
    }

    Output:

    Number of Admissions: :  123
    Student Name:  Bud
    Package Price :  8900.23