Skip to content

Go Structs

A struct (short for "structure") is a collection of fields. It allows you to group different types of data into a single custom type.

Defining a Struct

package main

import "fmt"

// person struct has a Name and an Age
type person struct {
    name string
    age  int
}

func main() {
    // 1. Basic initialization
    fmt.Println(person{"Bob", 20})

    // 2. Named fields (recommended for clarity)
    p := person{name: "Alice", age: 30}
    fmt.Println(p.name)

    // 3. Pointers to structs
    sp := &p
    fmt.Println(sp.age)

    // 4. Modifying a field
    sp.age = 51
    fmt.Println(p.age) // Now 51
}

Why use Structs?

  • Organization: Keep related data together (e.g., a User struct with ID, Email, and Password).
  • Method Receivers: You can attach functions (methods) to structs.
  • JSON/Database Mapping: Use "tags" to tell Go how to convert a struct to JSON or a database row.

Struct Tags

Tags are small pieces of metadata added to fields, usually to help with JSON.

1
2
3
4
5
type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

Important Notes

  • Zero Values: If you don't provide a value for a field, it gets its "zero value" (e.g., 0 for int, "" for string).
  • Exporting: If a struct field starts with a Capital Letter, it is public (exported). If it starts with a lowercase letter, it is private to its package.