In Go, a struct is a composite data type that groups together variables of possibly different types under a single name. It's similar to a class in object-oriented programming languages but without methods (methods are covered in the next section). Structs are fundamental for organizing and managing related data.
A struct in Go is defined using the type keyword followed by the struct name, the struct keyword, and a list of fields enclosed in curly braces. Each field has a name and a type.
Here's the basic syntax:
type StructName struct {
Field1 Type1
Field2 Type2
// ...
}
- **Field Name**: The name of the variable that holds the data.
- **Type**: The type of data the field can hold (e.g., `int`, `string`, `bool`).
## Examples
### Defining a Struct
Let's define a simple struct named `Person` with fields for `Name` and `Age`.
```go
type Person struct {
Name string
Age int
}
### Creating Instances of a Struct
You can create an instance of a struct in several ways:
#### 1. Using Field Names
```go
p := Person{
Name: "Alice",
Age: 30,
}
#### 2. Without Field Names (Order Matters)
```go
p := Person{"Bob", 25}
If you don't provide values for all fields, the omitted ones are initialized to their zero value.
p := Person{Name: "Charlie"}
// p.Age will be 0
You can access and modify struct fields using the dot notation.
fmt.Println(p.Name) // Output: Alice
fmt.Println(p.Age) // Output: 30
p.Age = 31
fmt.Println(p.Age) // Output: 31
Go supports embedding, where a struct can contain another struct. This is useful for creating complex data structures.
type Address struct {
Street string
City string
}
type Employee struct {
Person
ID int
Address // Embedding the Address struct
}
When you embed a struct, its fields are promoted to the outer struct. This means you can access them directly from an instance of the outer struct.
e := Employee{
Person: Person{Name: "David", Age: 40},
ID: 123,
Address: Address{Street: "Main St", City: "Anytown"},
}
fmt.Println(e.Name) // Output: David
fmt.Println(e.Street) // Output: Main St
You can also define and use structs without giving them a name. This is useful for short-lived data structures.
person := struct {
Name string
Age int
}{
Name: "Eve",
Age: 28,
}
fmt.Println(person.Name) // Output: Eve
While not covered in this section, it's worth noting that you can associate functions with structs to create methods. This is a powerful feature of Go and will be discussed in the next section.
In the next section, we'll explore how to define and use methods for structs, allowing them to have behaviors similar to classes in other languages. Stay tuned!