Go Structures
Let’s learn about Go structures.
Structures in Go are both very powerful and very popular and are used for organizing and grouping various types of data under the same name. Structures are the more versatile data types in Go, and they can even be associated with functions, which are called methods.
Note: Structures, as well as other user-defined data types, are usually defined outside the
main()
function or any other package function so that they have a global scope and are available to the entire Go package. Therefore, unless we want to make clear that a type is only useful within the current local scope and is not expected to be used elsewhere, we should write the definitions of new data types outside functions.
Defining new structures
When we define a new structure, we group a set of values into a single data type, which allows us to pass and receive this set of values as a single entity. A structure has fields, and each field has its own data type, which can even be another structure or slice of structures. Additionally, because a structure is a new data type, it is defined using the type
keyword followed by the name of the structure and ending with the struct
keyword, which signifies that we are defining a new structure.
Structure: Syntax details
The following code defines a new structure named Entry
:
Get hands-on with 1400+ tech skills courses.