Анонимная структура и поле на Голанге

Опубликовано: 20 Февраля, 2022

Структура или структура в Golang - это определяемый пользователем тип, который позволяет нам создавать группу элементов разных типов в единое целое. Любая сущность реального мира, имеющая некоторый набор свойств или полей, может быть представлена как структура.

Анонимная структура

В языке Go вам разрешено создавать анонимную структуру. Анонимная структура - это структура, не содержащая имени. Это полезно, когда вы хотите создать структуру, пригодную для одноразового использования. Вы можете создать анонимную структуру, используя следующий синтаксис:

имя_переменной: = структура {
// поля
} {// Field_values}

Обсудим эту концепцию на примере:

Example:

// Go program to illustrate the
// concept of anonymous structure
package main
  
import "fmt"
  
// Main function
func main() {
  
    // Creating and initializing
    // the anonymous structure
    Element := struct {
        name      string
        branch    string
        language  string
        Particles int
    }{
        name:      "Pikachu",
        branch:    "ECE",
        language:  "C++",
        Particles: 498,
    }
  
    // Display the anonymous structure
    fmt.Println(Element)
}

Выход:

{Pikachu ECE C++ 498}

Анонимные поля

В структуре Go вам разрешено создавать анонимные поля. Анонимные поля - это те поля, которые не содержат никакого имени, вы просто указываете тип полей, и Go автоматически использует этот тип в качестве имени поля. Вы можете создавать анонимные поля структуры, используя следующий синтаксис:

type struct_name struct {
    int
    bool
    float64
}

Важные моменты:

  • 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:

    // Go program to illustrate the
    // concept of anonymous structure
    package main
      
    import "fmt"
      
    // Creating a structure
    // with anonymous fields
    type student struct {
        int
        string
        float64
    }
      
    // Main function
    func main() {
      
        // Assigning values to the anonymous
        // fields of the student structure
        value := student{123, "Bud", 8900.23}
      
        // Display the values of the fields
        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