golang struct
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
Address Address
}
type Address struct {
Street string
City string
PostalCode string
}
func main() {
person := Person{
Name: "Alice",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "Wonderland",
PostalCode: "45678",
},
}
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
fmt.Println("Street:", person.Address.Street)
fmt.Println("City:", person.Address.City)
fmt.Println("Postal Code:", person.Address.PostalCode)
}
Explanation:
package main
: Indicates that this Go file belongs to themain
package, which is the entry point of the executable program.import "fmt"
: Imports thefmt
package, which provides functions for formatting input and output.type Person struct { ... }
: Defines a struct namedPerson
that contains fields forName
(string) andAge
(int), as well as anAddress
field of typeAddress
.type Address struct { ... }
: Defines a struct namedAddress
containing fields forStreet
(string),City
(string), andPostalCode
(string).func main() { ... }
: The entry point of the program. It creates an instance of thePerson
struct, initializes its fields, and prints out the values of its fields usingfmt.Println()
.
The program demonstrates how to define and use structs in Go, showing how to create instances of structs, initialize their fields, and access nested struct fields through dot notation.