In Go, structures (structs) are used to group together fields, which are variables associated with different data types. Unlike some other programming languages, Go does not have properties in the traditional sense, but you can achieve similar functionality using struct fields and methods.
Fields in a struct are defined within the struct type. Each field has a name and a type.
package main
import (
"fmt"
)
// Define the Person struct with fields
type Person struct {
FirstName string
LastName string
Age int
}
func main() {
// Initialize a Person instance
person := Person{
FirstName: "Alice",
LastName: "Johnson",
Age: 28,
}
// Access and print the fields
fmt.Printf("First Name: %s\\\\n", person.FirstName)
fmt.Printf("Last Name: %s\\\\n", person.LastName)
fmt.Printf("Age: %d\\\\n", person.Age)
}
Person Struct:
Person struct has three fields: FirstName, LastName, and Age.Person Instance:
Person with initial values for each field.Person instance using dot notation.The output of the above code will be:
First Name: Alice
Last Name: Johnson
Age: 28
You can define methods for structs to encapsulate functionality that operates on the struct's fields. Methods in Go are defined with a receiver, which specifies the type the method is associated with.
// Define a method to get the full name of the person
func (p Person) FullName() string {
return p.FirstName + " " + p.LastName
}
// Define a method to celebrate the person's birthday
func (p *Person) CelebrateBirthday() {
p.Age += 1
}
func main() {
// Initialize a Person instance
person := Person{
FirstName: "Alice",
LastName: "Johnson",
Age: 28,
}
// Use the FullName method
fmt.Printf("Full Name: %s\\\\n", person.FullName())
// Celebrate the person's birthday
person.CelebrateBirthday()
fmt.Printf("New Age after Birthday: %d\\\\n", person.Age)
}
FullName method concatenates the FirstName and LastName fields.CelebrateBirthday method increments the Age field. Note that this method has a pointer receiver (Person) to modify the struct.