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
age int
// here we are providing a name to nested struct field [anonymous filed]
// basically we are embedding the another struct[Address] fields to this struct[User]
Address
}
type Address struct {
city string
state string
pincode int
}
func main() {
user := User{"tejas", 23, Address{"madurai", "tamilnadu", 600001}}
fmt.Println("Name :", user.name)
fmt.Println("Age :", user.age)
// user variable can directly access the address struct fields
fmt.Println("City :", user.city)
fmt.Println("State :", user.state)
fmt.Println("Pincode :", user.pincode)
}Output:
Name : tejas
Age : 23
City : madurai
State : tamilnadu
Pincode : 600001

Comments
Post a Comment