Skip to main content

Posts

Showing posts with the label nested structs in go

Nested Struct in Go

A Struct which has a field of another struct is called Nested struct Example : package main import "fmt" type User struct { name string age int address Address } type Address struct { city string state string pincode int } func main() { // declare a struct variable & initialize it after var user1 User user1.name = "vicky" user1.age = 22 user1.address.city = "chennai" user1.address.state = "tamilnadu" user1.address.pincode = 600001 // declaration and initialization of nested struct user2 := User{"tejas", 23, Address{"madurai", "tamilnadu", 600001}} fmt.Println(user1) fmt.Println(user2) } Output: user 1 : {vicky 22 {chennai tamilnadu 600001}} user 2 : {tejas 23 {madurai tamilnadu 600001}} Important Note: we can embed an another struct into a struct by anonymously providing no name to the struct field package main import "fmt" type User struct { name string...