Lesson 11Organizing with Structs
Up to this point, you've used a variety of individual variables. When it has come to grouping or relating variables, you've learned about arrays, which group a number of values of the same type under a single variable name. There are also times when you want to associate a number of different variables to a single group. For instance, you can create a bank account item with fields that represent information about a bank account, such as an account holder, an account number, and a balance.
A struct is a data structure that includes a list of fields. Structs are an important aspect of any programming language in that they allow you to organize a group of variables into a related unit such as an account. This lesson takes a close look at the use of structs in Go.
DECLARING AND INITIALIZING A STRUCT
Structs allow you to create complex data types. A struct in Go can contain one or more fields. Each field in the struct must have a data type. You can use the struct
keyword to create a struct using syntax like this:
type structName struct {
field1 string
field2 float64
[…]
}
Listing 11.1 creates a struct named account
with two fields, accountNumber
and balance
, and assigns a value to each of ...
Get Job Ready Go now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.