Introduction
In Go, a struct is a composite data type that groups together zero or more values of different types. These values are called fields, and each field has a name and a type. Structs are used to create complex data types that aggregate values together. They’re similar to classes in object-oriented programming languages, but without inheritance and methods.
Declaring Structs
You can declare a struct type using the type
keyword, followed by the name of the struct, the struct
keyword, and a list of fields enclosed in curly braces {}
. Each field has a name and a type, separated by a space. For example:
type Person struct {
Name string
Age int
}
In this example, Person
is a struct type with two fields: Name
of type string
, and Age
of type int
.
Creating Struct Values
You can create a value of a struct type by listing the values of its fields in the same order as they were declared. For example:
p := Person{"Alice", 30}
In this example, p
is a Person
value. Its Name
field is "Alice"
and its Age
field is 30
.
Accessing Struct Fields
You can access the fields of a struct value using dot notation. For example:
name := p.Name // "Alice"
age := p.Age // 30
In this example, p.Name
accesses the Name
field of p
, and p.Age
accesses the Age
field of p
.
Modifying Struct Fields
You can modify the fields of a struct value using dot notation and the assignment operator =
. For example:
p.Age = 31
In this example, p.Age = 31
changes the Age
field of p
to 31
.
Structs in Functions
You can pass struct values to functions and return them from functions. For example:
func birthday(p Person) Person {
p.Age++
return p
}
p = birthday(p)
In this example, the birthday
function takes a Person
value, increments its Age
field, and returns the modified Person
. The line p = birthday(p)
updates p
with the returned Person
.
Conclusion
Structs in Go are a powerful tool for aggregating related data together. They’re a fundamental part of Go’s type system and are used extensively in Go’s standard library and in Go programs. By understanding how to use structs, you can write more organized and maintainable Go code.
I hope this helps! Let me know if you have any questions or if there’s anything else you’d like to learn about Go. 😊