View : 0

12/04/2026 18:16pm

EP.7 Go with Structs - Designing Flexible Data!

EP.7 Go with Structs - Designing Flexible Data!

#Data Design

#Pointers

#Methods

#Structs

#Go

Go with Structs - Designing Flexible Data!

Systematic data management is the heart of a good program, and in Go, we can easily achieve this with Structs that group related variables together, along with Methods that help us manage data efficiently.

What is a Struct?

A Struct (Structure) in Go is a grouping of related variables, such as name, age, and address, which helps us manage data easily and systematically.
Example of a Struct:

package main

import "fmt"

type Person struct {
    name string
    age  int
}

func main() {
    p := Person{name: "Alice", age: 25}
    fmt.Println(p.name, "is", p.age, "years old.")
}

 

Using Methods with Structs

Methods are functions associated with a Struct that allow us to flexibly manage the data within the Struct.
Example of a Method:

type Person struct {
    name string
    age  int
}

func (p Person) greet() {
    fmt.Printf("Hello, my name is %s.\n", p.name)
}

func main() {
    p := Person{name: "Bob", age: 30}
    p.greet() // Output: Hello, my name is Bob.
}

 

Pointers with Structs

Using Pointers with Structs allows us to update the values of variables within the Struct.
Example:

func (p *Person) setAge(newAge int) {
    p.age = newAge
}

func main() {
    p := Person{name: "Alice", age: 25}
    p.setAge(26)
    fmt.Println(p.name, "is now", p.age, "years old.")
}

 

Nested Structs

One Struct can contain another Struct as a member, enabling more complex data structures.
Example of a Nested Struct:

type Address struct {
    city  string
    state string
}

type Person struct {
    name    string
    address Address
}

func main() {
    p := Person{name: "John", address: Address{city: "Bangkok", state: "Thailand"}}
    fmt.Println(p.name, "lives in", p.address.city)
}