Golang by Example

Logo

Struct

Go provides a powerful way to define custom data types using structs. A struct is a composite data type that groups together variables (fields) under a single name. This allows you to create complex data structures that can represent real-world entities. Structs are defined using the struct keyword, followed by a list of fields enclosed in curly braces. Each field has a name and a type.

   
   type Person struct {
       Name string
       Age  int
   }

The code above defines a struct named Person with two fields: Name of type string and Age of type int. You can create an instance of a struct by using the struct type as a constructor.

Anonymous Structs

Anonymous structs are structs that do not have a name. They are useful when you need a temporary data structure without defining a separate type. You can create an anonymous struct by using the struct keyword directly.

Struct Tags

Struct tags are annotations that can be added to struct fields. They are often used for serialization, validation, and other purposes. Tags are defined as a string literal following the field type.


   type Person struct {
       Name string `json:"name"`
       Age  int    `json:"age"`
   }

In the example above, the struct fields Name and Age have JSON tags that specify how they should be serialized to JSON. The json:"name" tag indicates that the Name field should be represented as "name" in the JSON output.

💡 Quiz
Do you know class and object in OOP? How do you think struct is related to class?

Table of contents

Hello World - Begin with the classic Hello World program
Primitives - Learn about the basic data types in Go
Flow Control - Controlling the flow of your program
Struct - All about struct
Functions - Define and call functions
Methods and Interfaces - Methods and interfaces in Go
Error Handling - Handling errors idiomatically
Concurrency - Goroutines and channels
Anti Patterns - Anti patterns in Go
Libraries - Standard library and third-party libraries
Testing - Writing unit tests with `go test`
Benchmarking - Performance benchmarks
Containerization - Dockerize your Go app
What's Next? - Explore the next steps in your Golang journey


Share to: