golang

Golang Anonymous Struct

A structure refers to a user-defined type that allows you to organize multiple but related elements in a unit. We can think of a structure as a blueprint that represent a real-world entity or an object.

For example, we can create a structure to represent a car. We can then spin specific models of a car from that object.

What is An Anonymous Struct?

An anonymous struct is a structure that does not have a name. This means that we cannot reference the structure elsewhere in the code. Anonymous structures allow you to define ephemeral structures for one-time use.

An example syntax to create an anonymous structure is as shown:

variable_name := struct{

// fields

}{field_values}

Create Anonymous Struct

Consider the example below that illustrates how to create an anonymous struct.

package main
import "fmt"
funcmain() {
    // create anon struct
    car := struct {
        manufacturer, year, model string
        mileage                   int
        price                     float64
    }{
        manufacturer: "Toyota",
        model:        "Camry",
        mileage:      200000,
        year:         "2018",
        price:        24380.00,
    }
    // print anon struct
    fmt.Println(car)
}

In the example above, we create an anonymous struct and create an instance of the struct immediately.

The above code should print the struct as:

{Toyota 2018 Camry 200000 24380}

Anonymous Fields

Go allows you to create anonymous fields. As the name suggests, these are struct fields that do not have a name.

The syntax is as shown:

type struct_name struct {

int

string

bool

}

If you are creating anonymous fields, you cannot have more than one field of the same type. For example:

type struct_name struct {

string

string

}

The above syntax should return an error.

Consider the example below to create a struct with anonymous fields.

package main
import "fmt"

funcmain() {
    type car struct {
        string
        int
        float64
    }
    camray := car{"Toyota Camry", 200000, 24380.00}
    // print values
    fmt.Println("Model: ", camray.string)
    fmt.Println("Mileage: ", camray.int)
    fmt.Println("Price: ", camray.float64)
}

The above code should return:

Model: Toyota Camry

Mileage: 200000

Price: 24380

Conclusion

This guide covers what anonymous structures are, how to create them in Go and how to implement anonymous fields in a Go structure.

Happy Coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list