A struct (short for structure) in Go is a composite data type that groups together variables under a single name, allowing you to create complex data types. Think of structs as blueprints for creating your own custom data types.
Here's how you declare a struct type called Person
:
type Person struct { Name string Age int Email string }
You can create and initialize a struct variable like this:
// Using a struct literal person1 := Person{Name: "Alice", Age: 30, Email: "alice@example.com"} // Using var and then assigning fields var person2 Person person2.Name = "Bob" person2.Age = 25 person2.Email = "bob@example.com"
Access or modify fields using the dot notation:
fmt.Println(person1.Name) // Output: Alice person2.Age = 26 fmt.Println(person2.Age) // Output: 26
You can create pointers to structs, which allows you to modify the original struct via the pointer:
personPtr := &person1 personPtr.Age = 31 fmt.Println(person1.Age) // Output: 31
Notice how changing Age
via the pointer updates the original struct.
Sometimes you can use structs without defining a named type:
user := struct { Username string Active bool }{ Username: "golangfan", Active: true, } fmt.Println(user.Username) // Output: golangfan
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!