Thuta Learning
IntermediateProgrammingbeginner

Structs

Relax. We'll talk through this in plain words — no textbook voice.

Struct is a custom data type that groups fields together. Go doesn't have classes, but you can model real-world objects using struct + method style. Structs are super useful for data shapes like User, Product, Order, and Post.

go
package main

import "fmt"

type User struct {
    Name  string
    Email string
    Age   int
}

func main() {
    user := User{Name: "Aung", Email: "aung@example.com", Age: 25}
    fmt.Println(user.Name)
    fmt.Println(user.Email)
}

type User struct creates a data shape called User. If you start field names with a capital letter, they can be accessed from outside the package.

You should see
Aung aung@example.com

Info

Writing out field names in a struct literal makes it more readable. User{"Aung", "aung@example.com", 25} works too, but if you get the field order wrong, it's an easy way to introduce bugs.

Easy traps

  • If a field name starts with lowercase, other packages can't access it. Watch out for the export rule when writing data models for a public API.
Structs | Thuta Learning