Learn Go← Dashboard

Compose your own types from named fields.

Defining and Using Structs

A struct bundles named fields into one value. It's Go's equivalent of a class — minus the inheritance, minus the constructors.

Declaring a struct

go playground
Loading...

Composite literals

You can construct a struct in three ways:

p := Point{X: 1, Y: 2}    // by field name (recommended)
p := Point{1, 2}          // positional — must include every field
p := Point{}              // zero values (X=0, Y=0)

Always prefer the named form — when someone adds a field, your code keeps compiling.

Pointers to structs

You'll usually pass structs around as pointers — to avoid copying and to allow mutation. Note that you can write p.X even when p is a pointer; Go auto-dereferences.

go playground
Loading...

Comparing structs

If every field is comparable, structs are comparable too:

a := Point{1, 2}
b := Point{1, 2}
fmt.Println(a == b)   // true

You can also use a struct directly as a map key.

Anonymous structs

Sometimes you want a one-off struct, often for JSON decoding:

var resp struct {
    Name  string `json:"name"`
    Score int    `json:"score"`
}
json.NewDecoder(r).Decode(&resp)
fmt.Println(resp.Name)

Useful when defining a named type would be overkill.

The empty struct struct{}

struct{} has zero size — it takes no memory. Two common uses:

  • Set semantics: map[string]struct{} is "set of strings" without wasting a bool.
  • Signaling channels: chan struct{} is a "wake me up" pulse that carries no data.
seen := map[string]struct{}{}
seen["x"] = struct{}{}
_, ok := seen["x"]   // true
Why prefer `Point{X: 1, Y: 2}` over `Point{1, 2}`?