0Pricing
Go Academy · Lesson

Anonymous Structs and Composition

Embedding and struct-based code reuse

Anonymous Structs

An anonymous struct has no named type. It's defined inline and is useful for short-lived data, table-driven tests, and one-off groupings:

package main
import "fmt"

func main() {
    point := struct{ X, Y int }{X: 3, Y: 7}
    fmt.Println(point.X, point.Y)
}

Anonymous Structs in Table Tests

A common Go idiom uses a slice of anonymous structs for table-driven tests:

package main
import "fmt"

func double(n int) int { return n * 2 }

func main() {
    tests := []struct{ input, want int }{
        {1, 2}, {5, 10}, {0, 0},
    }
    for _, tt := range tests {
        got := double(tt.input)
        if got != tt.want {
            fmt.Printf("FAIL: double(%d) = %d, want %d\n", tt.input, got, tt.want)
        }
    }
    fmt.Println("all tests passed")
}

All lessons in this course

  1. Defining and Using Structs
  2. Methods on Structs
  3. Constructor Patterns
  4. Anonymous Structs and Composition
← Back to Go Academy