In Go, structures (structs) are used to define custom data types by grouping together different fields of various types.
Here's how you can define and use structures in Go:
Defining a structure:
type Person struct {
Name string
Age int
Address string
}
This defines a struct type Person
with three fields: Name
(string), Age
(int), and Address
(string).
Creating an instance of the structure:
p := Person{
Name: "John Doe",
Age: 30,
Address: "123 Main St",
}
Here, we create a new instance p
of the Person
struct and initialize its fields with values using a struct literal.
Accessing structure fields:
fmt.Println(p.Name) // Output: John Doe
fmt.Println(p.Age) // Output: 30
fmt.Println(p.Address) // Output: 123 Main St
You can access individual fields of a struct by using the dot (.
) operator followed by the field name.
Modifying structure fields:
p.Age = 40
Fields of a struct can be modified by assigning new values to them.
Structs can also be used as fields within other structs, allowing you to create nested structures.
For example:
type Location struct {
Latitude float64
Longitude float64
}
type Place struct {
Name string
Location Location
}
In the above example, Place
struct contains a field Location
of type Location
struct.
You can use structs to define complex data structures, create custom types, and group related data together for efficient handling.