Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Anonymous Structs and Embedded Fields in Go

Create an unnamed struct, declare a named field with an inline struct type, and use embedding to promote fields without confusing it with inheritance.

Table of Contents

An anonymous struct is a struct type declared without a type name. An embedded field is a field declared with a type name and no explicit field name. These are separate features. You can declare a named field whose type is an anonymous struct.

Anonymous structures and fields in Golang Picture 1

Create a value of an unnamed struct type

Use a struct literal when a small group of values is only needed near the code that creates it.

student := struct {
    Name string
    GPA  float64
}{Name: "Ava", GPA: 3.8}

fmt.Println(student.Name, student.GPA)

Place the snippet inside a function in a file that imports fmt. To put an inline struct inside another one, write a named field such as Details struct { Enrollment int } and access it as student.Details.Enrollment.

Embed a named type to promote its fields

type Person struct {
    Name string
}

type Student struct {
    Person
    GPA float64
}

student := Student{Person: Person{Name: "Ava"}, GPA: 3.8}
fmt.Println(student.Name)        // Ava
fmt.Println(student.Person.Name) // Ava

The last three lines belong inside a function. Person is the embedded field’s name. Its Name field can also be selected directly as student.Name, as long as there is no ambiguity. Initialize the embedded Person explicitly in a keyed literal.

Know which declarations are valid

struct { First int; Second int } is valid because the field names differ. Embedding int twice would create two fields named int and is invalid. You can combine a field named ID of type int with an embedded int, although names that explain the data are often clearer. See the Go specification for struct types.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.