GO Tutorial



STRUCTS IN GO


Structs in Go

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.

Defining a Struct

Here's how you declare a struct type called Person:

type Person struct {
    Name   string
    Age    int
    Email  string
}
    

Creating Struct Variables

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"
    

Accessing Struct Fields

Access or modify fields using the dot notation:

fmt.Println(person1.Name)  // Output: Alice

person2.Age = 26
fmt.Println(person2.Age)   // Output: 26
    

Structs and Pointers

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.

Anonymous Structs

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
    
Why use structs?
  • Group related data together logically.
  • Create reusable and organized data models.
  • Pass complex data as a single unit in functions.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review