Structs in Golang (Like a Blueprint for Your Data!)

In Go, structs are like blueprints for creating custom data types. If maps are treasure chests, then structs are the entire pirate ship—designed exactly the way you want! 

1. What is a Struct?

A struct (short for structure) is a collection of fields grouped together under a single name. It allows you to create complex data types that model real-world objects.

Declaring a Struct

package main
import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    var p Person // Creating an empty struct
    fmt.Println(p) // Output: { "" 0 }
}

Structs allow you to define your own data structures, like a custom-built Lego character! 

2. Initializing Structs

You can initialize a struct using different methods:

package main
import "fmt"

type Car struct {
    Brand string
    Year  int
}

func main() {
    car1 := Car{"Toyota", 2022}
    car2 := Car{Brand: "Tesla", Year: 2023}
    fmt.Println(car1, car2)
}

This is like setting up your dream car collection!

3. Accessing and Modifying Struct Fields

You can access and modify struct fields using dot notation:

package main
import "fmt"

type Book struct {
    Title  string
    Author string
}

func main() {
    myBook := Book{"The Go Programming Language", "Alan A. A. Donovan"}
    fmt.Println("Before:", myBook)
    myBook.Author = "John Doe" // Changing the author
    fmt.Println("After:", myBook)
}

Just like updating your favorite book's cover, but in code form!

4. Structs with Methods

You can attach methods to structs, making them act more like real-world objects with behaviors!

package main
import "fmt"

type Animal struct {
    Name string
}

func (a Animal) Speak() {
    fmt.Println(a.Name, "says Woof!")
}

func main() {
    dog := Animal{"Buddy"}
    dog.Speak()
}

Now our dog can "speak" (kind of). 

5. Nested Structs

You can put a struct inside another struct, like a Russian nesting doll. 

package main
import "fmt"

type Engine struct {
    Horsepower int
}

type Car struct {
    Brand  string
    Engine Engine
}

func main() {
    myCar := Car{"Ford", Engine{250}}
    fmt.Println(myCar.Brand, "has", myCar.Engine.Horsepower, "HP")
}

Now your car has an engine inside it! 

Structs are the backbone of complex data modeling in Go. Whether you're building a game character, a database model, or a spaceship, structs give you full control over your data. Now go forth and build your own blueprints! 

Post a Comment

0 Comments