Go struct types¶
In Go, a struct is a typed collection of fields used to group data together.^[400-devops-09-scripting-language-golang-introduction-readme.md] It is particularly useful for modeling entities that possess multiple properties, such as a customer with a first name, last name, and full name.^[400-devops-09-scripting-language-golang-introduction-readme.md] Structs allow developers to aggregate various variables into a single, cohesive variable type.^[400-devops-09-scripting-language-golang-introduction-readme.md]
Definition¶
A struct is defined by specifying the type keyword followed by the type name and the struct keyword. Inside the block, fields are listed with their names and data types.^[400-devops-09-scripting-language-golang-introduction-readme.md] For example, a Customer struct might be defined as follows^[400-devops-09-scripting-language-golang-introduction-readme.md]:
type Customer struct {
FirstName string
LastName string
FullName string
}
Usage¶
Structs are typically used to create data structures that can be returned by functions or iterated over in loops.^[400-devops-09-scripting-language-golang-introduction-readme.md] When a function returns a slice of a struct type, the caller can access the specific fields of each instance using dot notation (e.g., customer.FirstName).^[400-devops-09-scripting-language-golang-introduction-readme.md]
This allows for more organized and readable code compared to managing individual variables or flat arrays.^[400-devops-09-scripting-language-golang-introduction-readme.md]
Related Concepts¶
- [[Slices]]
- [[Loops]]
Sources¶
400-devops-09-scripting-language-golang-introduction-readme.md