From the course: Go for Developers: Practical Techniques for Effective Coding
Unlock this course with a free trial
Join today to access over 24,900 courses taught by industry experts.
Structs - Go Tutorial
From the course: Go for Developers: Practical Techniques for Effective Coding
Structs
- A struct is a collection of fields. It is used to create custom complex types in Go. When trying to understand structs, it helps to think of them as a blueprint for what the new type will do. A struct definition does not contain any data. Before we can start working with structs, we need to first understand how to declare new types in Go. To declare a new type in Go, we use the type keyword and give it a name. Like all identifiers in Go, the type's name must be unique within the package and follow the naming conventions for Go identifiers. Finally, all new types must be based on an existing type. For example, here we have defined three types, MyInt, My String, and MyMap. Each of these new types is based on an existing type, like MyInt is based on the int type. We can use these new types just like we have with the other types we've encountered. For example, we can use the var keyword to create a new variable of type MyInt and assign it to the value 1. Basic data types, such as int…