Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Nested Struct in Go (Golang)

Posted on June 14, 2023June 14, 2023 by admin

A struct can have an another struct nested in it. Let’s see an example of a nested struct. In below employee struct has address struct nested it in.

package main
import "fmt"
type employee struct {
name string
age int
salary int
address address
}
type address struct {
city string
country string
}
func main() {
address := address{city: "London", country: "UK"}
emp := employee{name: "Sam", age: 31, salary: 2000, address: address}
fmt.Printf("City: %s\n", emp.address.city)
fmt.Printf("Country: %s\n", emp.address.country)
}

Output

City: London
Country: UK

Notice how nested struct fields are accessed.

emp.address.city
emp.address.country
  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP