V
Vel·ToolKit
Simple · Fast · Ready to use
EN
Chapter 10 of 20

Structs

Definition, initialization, embedded composition

Definition and Literals

package main

import "fmt"

type User struct {
    ID   int
    Name string
    Age  int
}

func main() {
    u1 := User{1, "Alice", 30}
    u2 := User{ID: 2, Name: "Bob"} // partial fields; omitted ones take the zero value
    fmt.Println(u1, u2)
}

Field Access and Pointers

Whether you hold a struct or a pointer to a struct, field access uses .; Go dereferences automatically.

package main

import "fmt"

type User struct {
    ID   int
    Name string
}

func main() {
    p := &User{Name: "Carol"}
    fmt.Println(p.Name) // no need for (*p).Name
}

Composition (Embedded Fields)

Go has no inheritance, but embedded fields provide "composition". The outer struct can directly use the embedded struct's fields and methods.

package main

import "fmt"

type Animal struct{ Name string }

func (a Animal) Greet() { fmt.Println("Hi, I am", a.Name) }

type Dog struct {
    Animal // embedded
    Breed  string
}

func main() {
    d := Dog{Animal{"Rex"}, "Husky"}
    d.Greet() // directly calls Animal's method
    fmt.Println(d.Breed)
}

Struct Tags

The backtick string after a field is a tag, commonly read by libraries (JSON, ORM, form validation, etc.) for metadata.

package main

import (
    "encoding/json"
    "fmt"
)

type Article struct {
    Title string `json:"title"`
    Body  string `json:"body,omitempty"`
}

func main() {
    b, _ := json.Marshal(Article{Title: "Go"})
    fmt.Println(string(b)) // {"title":"Go"}
}

Comparison

A struct is comparable only if all its fields are comparable (slices and maps are not comparable). A comparable struct can be used as a map key.