99devops

99devops

A highly trained monkey’s blog

24 Apr 2022

Anonymous structs in Go

In this article we will see how anonymous structs works in golang. Generally in go, structs are declared as

type person struct {
    Name string
    Age int8
    Address string
}

and later a new variable is created of the above struct type like below

person := Person{"Prabesh",29,"Australia"}

but instead of this you can also use anonymous structs, which is a subtle feature of go lang. It makes it easier for you to avoide creating extra struct types.

You can create anonymous structs in go like this


func main() {
    // Creating a new variable using anonymous structs
    person := struct {
        Name string
        Age int8
        Address string
    }{
        Name: "Prabesh",
        Age: 29,
        Address: "Australia",
    }
}

Such implementation of anonymous structs are seen commonly while creating unit tests in go.

Here is a full program with its output

package main

import "fmt"

func main() {
	// Creating a new variable using anonymous structs
	person := struct {
		Name    string
		Age     int8
		Address string
	}{
		Name:    "Prabesh",
		Age:     29,
		Address: "Australia",
	}
	fmt.Printf("%v age is %v and he lives in %v\n", person.Name, person.Age, person.Address)
}

Output:

➜  golearn go run main.go

Prabesh age is 29 and he lives in Australia
comments powered by Disqus