Loading, please wait...

A to Z Full Forms and Acronyms

Explain Anonymous Structure and Anonymous Fields in GoLang | Go Programming Tutorial

Oct 18, 2022 #GoLanguage #GoProgramming #GoTutorial, 1317 Views
In this article, you will learn: What is Anonymous Structure in GoLang? What are Anonymous Fields in GoLang?

Explain Anonymous Structure and Anonymous Fields in GoLang | Go Programming Tutorial

In this article, you will learn:

  • What is Anonymous Structure in GoLang?
  • What are Anonymous Fields in GoLang?

A struct in GoLang is a user-defined type, which combines the variables of different types into a single unit. Any object which has some properties or fields can be represented as a struct.

What is Anonymous Structure in GoLang?

GoLang has a feature to create an anonymous structure. An anonymous struct is a kind of structure that does not contain any name. In simple words, a structure declared without a name is an anonymous structure. It is useful when the user wants to create a one-time usable structure. With the help of the following you can create a structure:

variable_name := struct {

 // fields

} { // Value_of_Fields}

What are Anonymous Fields in GoLang?

In the GoLang structure, the user can create anonymous Fields. It is the kind that does not contain any name, just mention the type of the fields, and Go will automatically consider the type as the name of the field. In the following way, you can create structure:

type nameofstruct struct{

  string 

  int

  float

}

Example:

package main
import "fmt"
  
// Main function
func main() {
  
    // Create and initialize the anonymous structure
    values := struct {
        name      string
        branch    string
         roll_no int
    }{
        name:      "John",
        branch:    "CSE",
         roll_no:   498,
    }
  
    // Display the anonymous structure
    fmt.Println(values)
}

Output:

{ John, CSE, 498}

Points to be remembered: 

  • In an anonymous structure, the user is not allowed to create two or more fields of the same data type. If you try to do so, the compiler will give you an error.
  • The user can combine the anonymous field with the name fields.
A to Z Full Forms and Acronyms