Welcome to our comprehensive guide on Go Struct Definition! This lesson is designed to help both beginners and intermediate learners understand the concept of structs in the Go programming language. Let's dive in! 📝
In Go, a struct (short for structure) is a custom data type that allows you to combine multiple data elements into a single entity. Structs are essential for organizing complex data in a structured manner, making your code cleaner and easier to manage. 💡
To create a struct, you define a type with the type keyword followed by the struct name and a set of fields enclosed within curly braces {}. Here's an example of a simple struct named Person:
type Person struct {
FirstName string
LastName string
Age int
}In this example, Person is a custom data type that contains three fields: FirstName, LastName, and Age. Each field has its own data type: string and int.
To access the fields of a struct, you use the dot (.) operator followed by the field name. Here's an example of how to access the fields of the Person struct:
func main() {
var john Person
john.FirstName = "John"
john.LastName = "Doe"
john.Age = 30
fmt.Println(john.FirstName, john.LastName, john.Age)
}In this example, we've created a Person variable named john and assigned values to its fields. The fmt.Println() function is then used to print the values of the FirstName, LastName, and Age fields.
In addition to fields, structs can also have methods associated with them. Methods in Go are functions that are attached to a struct type and have access to the struct's fields. 💡
Here's an example of a Person struct with a method called Display that prints the person's details:
type Person struct {
FirstName string
LastName string
Age int
}
func (p Person) Display() {
fmt.Println("Name:", p.FirstName, p.LastName)
fmt.Println("Age:", p.Age)
}
func main() {
var john Person
john.FirstName = "John"
john.LastName = "Doe"
john.Age = 30
john.Display()
}In this example, the Display method is defined with a receiver parameter p of type Person. The method then uses the dot operator (.) to access the FirstName, LastName, and Age fields of the Person struct.
What is a struct in Go?
By understanding structs and struct methods in Go, you'll be able to organize and manipulate complex data with ease. In the next lesson, we'll dive deeper into struct methods and explore some practical use cases. Happy coding! 💡