Structs in Go
Go programming language provides a data type called struct
which allows us to group/combine items of possibly different types into a single type. It's a composite data type, which is used to group together zero or more values of any type, represented by fields. It's a way to create more complex data types that can be used to describe larger pieces of data or concepts.
Defining a Struct
You can create a struct type using the type
and struct
keywords. Here's an example of a struct type that stores information about a person:
type Person struct {
Name string
Age int
}
In the above code, we have defined a Person
struct with two fields, Name
of type string
and Age
of type int
.
Creating Struct Instances
You can create instances of the struct using the struct literal syntax:
p := Person{"Bob", 20}
In this example, p
is an instance of Person
. We've initialized it with the name "Bob" and age 20.
Accessing Struct Fields
You can access the fields in a struct using a dot (.
):
fmt.Println(p.Name) // Outputs: Bob
Pointers to Structs
Structs can be pointed to with pointers. The pointer's type is the type of the struct it points to. For example:
p := &Person{"Alice", 30}
In this case, p
is a pointer to a Person
struct. You can access fields in a struct that a pointer points to in the same way you would if it wasn't a pointer:
fmt.Println(p.Age) // Outputs: 30
Go automatically dereferences the pointer.
Nested Structs
Structs can also be nested. This means a struct can contain fields that are structs themselves. For example:
type Employee struct {
Person
Position string
}
e := Employee{Person{"Bob", 20}, "Developer"}
In this case, Employee
is a struct that has a Person
struct as a field, and a Position
field of type string
.
Anonymous Structs
Go also supports anonymous structs, which can be useful when you want to create a one-off struct that won’t be reused elsewhere. Here's an example:
point := struct {
X, Y int
}{10, 20}
fmt.Println(point) // Outputs: {10 20}
In this case, we've created an anonymous struct with fields X
and Y
, and we've initialized it with the values 10 and 20.
In conclusion, structs in Go provide a powerful way to group and organize related pieces of data. They form the basis for creating complex data types and modeling real-world entities.