×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Structures

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Anonymous Structure and Field

Last Updated : July 22, 2025

In Go, anonymous structures are struct types declared and used without being explicitly named. Anonymous fields (also known as embedded fields) allow you to include fields from other structs without explicitly naming them.

Anonymous Structure

You can define and use an anonymous struct without declaring a named type. It is often used when you need a temporary or one-off struct.

Example

The following example shows how to define and use an anonymous struct in Go:

package main
import "fmt"

func main() {
    person := struct {
        name string
        age  int
    }{
        name: "Rahul",
        age:  28,
    }

    fmt.Println("Name:", person.name)
    fmt.Println("Age:", person.age)
}

When you run the above code, the output will be:

Name: Rahul
Age: 28

Anonymous Fields (Embedded Fields)

In Go, you can embed a struct inside another struct without naming the field. This allows the inner struct's fields to be accessed directly through the outer struct.

Example

The following example demonstrates how anonymous fields work:

package main
import "fmt"

type Address struct {
    city  string
    state string
}

type Employee struct {
    name string
    Address // Anonymous field
}

func main() {
    emp := Employee{
        name: "Priya",
        Address: Address{
            city:  "Mumbai",
            state: "Maharashtra",
        },
    }

    fmt.Println("Name:", emp.name)
    fmt.Println("City:", emp.city)
    fmt.Println("State:", emp.state)
}

When you run the above code, the output will be:

Name: Priya
City: Mumbai
State: Maharashtra

Go Anonymous Structure and Field Exercise

Select the correct option to complete each statement about anonymous structures and fields in Go.

  1. An anonymous structure is:
  2. Anonymous fields allow:
  3. Which of the following is true about anonymous fields?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.