Struct as record
A struct used as a record is a fixed, named bundle of fields you pass as one value: a row, a coordinate, a key. It is data, not an object hierarchy. Use it when a map of string keys would lose types and names.
Detailed Explanation
You are returning a user ID, a name, and an email from a query. Three return values work once. A type User struct { ID int64; Name, Email string } works everywhere: as a slice element, a map value, a JSON object, a function argument. That is a record. Go does not have a separate record keyword (Java does). The struct is the record.
When a struct beats a map. map[string]any can grow new keys at runtime and forget to include email. A struct makes missing fields a compile error at the literal, and it gives each field a type. Use a map when the keys are not known at compile time (headers, query parameters, JSON you have not modelled). Use a struct when they are.
When a struct beats a tuple. Go has no tuple type. (string, int) as a return is a tiny tuple. Once you pass that pair into a third function, name it: type Pair struct { Path string; Status int }. Named fields survive reordering; positional returns do not.
Comparable records as keys. A struct of comparable fields can be a map key: map[Point]int for a grid. A struct that contains a slice cannot. Keep key structs small and free of slices and maps.
Zero record. var u User is a real user with empty strings and 0 IDs. Decide whether that zero is "unset" or a valid row. For IDs, 0 is often invalid; document it or use a pointer field / a separate ok from the lookup.
What it costs. A record is the size of its fields plus padding. Copying a large record on every call is why you pass *User once the row grows. There is no object header. A []User is packed rows, which is cache-friendly compared to a slice of maps.
Code Examples
package main
import "fmt"
type User struct {
ID int64
Name string
Email string
}
func main() {
u := User{ID: 1, Name: "Ada", Email: "ada@example.com"}
fmt.Println(u.Name)
}type Point struct{ X, Y int }
func grid() map[Point]int {
return map[Point]int{{1, 2}: 7}
}type Pair struct {
Path string
Status int
}
func result() Pair {
return Pair{Path: "/health", Status: 200}
}Common Gotchas
Positional literals break when you add a field
`User{1, "Ada", "a@b"}` will not compile after a fourth field, or worse, will compile if the new field type lines up. Use keys.
A zero struct is not "no row"
distinguish missing with a pointer, comma-ok, or an extra bool.
Records with slice fields are not comparable
they cannot be map keys and cannot use `==`.
This is not a Java class
no inheritance, no constructors. Add methods if behaviour belongs on the record; keep them small.