Structs

Contents

Structs#

A struct is a record. Fields are typed and ordered. Methods attach to named types (see OOP).

Declare and construct.

type User struct {
    ID    string
    Name  string
    Email string
}

u := User{ID: "1", Name: "rk"}

Field assignment.

u.Email = "rk@example.com"

Pointer to struct; field access auto-dereferences.

p := &u
p.Name = "operator"

Anonymous structs are useful inline.

point := struct{ X, Y int }{3, 4}

References#

  • Pointers for the *T form used with structs.

  • OOP for methods, embedding, and the receiver forms.