Go - Nested Structs Example

Go structs can be nested so in this example, we show how to create nested structs in Golang with an example.

Go - nested structs example

In the example, the Address struct is nested inside the User struct:

package main

import "fmt"

type Address struct {
    city    string
    country string
}

type User struct {
    firstName    string
    lastName     string
    email        string
    address Address
}

func main() {

    user := User{
        firstName:      "John",
        lastName: 		"Cena",
        email:        	"cena@gmail.com",
	address: Address{
            city:    "Mumbai",
            country: "India",
        },
    }
	
    fmt.Println("firstName:", user.firstName)
    fmt.Println("lastName:", user.lastName)
    fmt.Println("City:", user.address.city)
    fmt.Println("Country:", user.address.country)
}

Output:

firstName: John
lastName: Cena
City: Mumbai
Country: India

Comments