Structs

Go Structs

Defining Structs

Go structs define custom types with fields and methods.

Introduction to Go Structs

In Go, structs are a way to define custom data types. A struct is a composite data type that groups together variables under a single name. These variables, known as fields, can be of different types. Structs are useful for grouping data to form records.

Defining a Struct

You can define a struct in Go using the type and struct keywords. Below is an example of how to define a simple struct for a Person.

Creating an Instance of a Struct

Once you have defined a struct, you can create an instance of it. Here's how you can create a Person instance and assign values to its fields.

Accessing and Modifying Struct Fields

You can access and modify the fields of a struct using the dot (.) operator. Below is an example of how to access and modify the fields of a Person.

Anonymous Structs

Go also supports anonymous structs, which are useful for short-lived data structures that you don't need to reuse. Here's an example of an anonymous struct.

Structs with Nested Fields

Structs in Go can also contain other structs as fields, allowing you to create complex data structures. Here's an example demonstrating nested structs.

Conclusion

Go structs are powerful tools for creating complex data types with ease. They provide a way to logically group data and methods, enabling you to build scalable and efficient applications. In the next post, we'll explore how to associate methods with structs, enhancing their functionality.