When to Use a Pointer to a Struct vs a Value in Go

Use pointers for large or mutable structs to avoid copying, and values for small or immutable data to ensure safety.

Use a pointer to a struct when you need to modify the original data, avoid copying large structs, or pass the struct to functions that expect a pointer (like cgo wrappers). Use a value when the struct is small, immutable, or you need a local copy.

// Use pointer for large structs or modification
type Int struct {
    i    C.mpz_t
    init bool
}

func (z *Int) SetInt64(x int64) *Int {
    z.doinit()
    C.mpz_set_si(&z.i[0], C.long(x))
    return z
}

// Use value for small, immutable structs
type Point struct {
    X, Y int
}

func NewPoint(x, y int) Point {
    return Point{X: x, Y: y}
}