In Go, structs are the primary way to group related data together into a single, composite type. They are similar to classes in other languages but without inheritance.

Structs are especially useful when you want to represent real-world entities or complex objects with multiple fields.


1️⃣ Defining a Struct

type Person struct {
    Name string
    Age  int
    Email string
}

2️⃣ Creating Struct Values

// Using field names
p1 := Person{Name: "Alice", Age: 30, Email: "[email protected]"}

// Using positional fields
p2 := Person{"Bob", 25, "[email protected]"}

// Empty struct
p3 := Person{} // all fields get zero values

3️⃣ Accessing and Modifying Fields

fmt.Println(p1.Name) // Alice
p1.Age = 31          // update field

4️⃣ Structs and Methods

You can attach methods to structs to give them behavior:

func (p Person) Greet() string {
    return "Hello, my name is " + p.Name
}

fmt.Println(p1.Greet()) // Hello, my name is Alice

5️⃣ Purpose and Use Cases

Purpose Explanation
Data grouping Combine related fields (like a record or object).
Model real-world entities Represent things like User, Order, Car, etc.
Attach behavior Methods can be defined on structs.
Type safety Each struct is a distinct type.
Composability Structs can embed other structs to share fields.