VOOZH about

URL: https://www.geeksforgeeks.org/go-language/anonymous-structure-and-field-in-golang/

⇱ Anonymous Structure and Field in Golang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Anonymous Structure and Field in Golang

Last Updated : 5 Nov, 2024

In Golang, structures (or structs) allow us to group elements of various types into a single unit, which is useful for modeling real-world entities. Anonymous structures are unnamed, temporary structures used for a one-time purpose, while anonymous fields allow embedding fields without names.

Example:

Syntax

variable := struct { field1 dataType1 field2 dataType2 # Anonymous Structure
 // Additional fields as needed}{value1, value2}type StructName struct { dataType1 dataType2 # Anonymous Fields  // Additional anonymous fields}

Anonymous Structure

An anonymous structure in Go is defined without a name and is useful for creating a one-time, temporary structure. Here’s the syntax and a code example.

Syntax

variable := struct {
 field1 dataType1
 field2 dataType2
 // Additional fields as needed
}{value1, value2}

Example


Output
Name: A
Enrollment: 12345
GPA: 3.8

In this code, we define a Student structure with an anonymous personalDetails structure inside it, which stores name and enrollment. We then initialize student with values for these fields and print them out.

Anonymous Fields

Anonymous fields in Go allow you to define fields without explicit names, only specifying their types. This is beneficial when fields naturally follow type names.

Syntax

type StructName struct {
 dataType1
 dataType2
 // Additional anonymous fields
}

Example


Output
Enrollment: 12345
Name: A
GPA: 3.8

Here, the data types (int, string, float64) act as the field names, so accessing the values relies on the types.

Important Points about Anonymous Fields

1. Uniqueness Requirement: You cannot use two fields of the same type in a struct. For example:

type InvalidStudent struct {
 int
 int // Error: duplicate type
}

2. Combining Named and Anonymous Fields: You can mix anonymous and named fields within a struct.

type Student struct {
 id int // Named field
 int // Anonymous field
}
Comment
Article Tags:
Article Tags:

Explore