Introduction to Go Structs
In Go (Golang), a struct is a composite data type that allows you to group together zero or more fields of different data types under a single name. Structs provide a way to represent real-world entities and organize related data. This tutorial will guide you through the basics of working with structs in Go, including declaration, initialization, field access, and methods.
Declaring a Struct
To declare a struct in Go, you use the type
keyword followed by the struct’s name and a list of fields inside curly braces {}
. Here’s a simple example:
package main
import "fmt"
// Define a struct named 'Person'
type Person struct {
Name string
Age int
}
Initializing a Struct
Once you’ve defined a struct, you can create instances of it by initializing the fields. There are several ways to initialize a struct in Go. One common method is using a struct literal:
// Initializing a struct using a struct literal
p := Person{Name: "Alice", Age: 30}
Accessing Struct Fields
You can access the fields of a struct using the dot (.
) operator. For example:
fmt.Println("Name:", p.Name) // Output: Name: Alice
fmt.Println("Age:", p.Age) // Output: Age: 30
Struct Methods
In Go, you can define methods on structs. A method is a function associated with a particular type. Let’s define a method Greet
for the Person
struct:
func (p Person) Greet() {
fmt.Println("Hello, my name is", p.Name)
}
Now, you can call this method on a Person
instance:
p.Greet() // Output: Hello, my name is Alice
Conclusion
Structs are a fundamental feature of Go programming, allowing you to organize data into custom types efficiently. In this tutorial, you’ve learned how to declare, initialize, access fields, and define methods on structs. With this knowledge, you can start building more complex data structures and applications in Go.