<!-- Structs and methods · Tin · https://tin.ad/docs/learn/structs/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 5 of 34

# Structs and methods

**Goal.** Define your own types with fields and methods, and group values with tuples.

## Your own types

A struct groups several values under one name. You declare it once with `type`, then build values
of it by giving every field.

*struct.tin · tin run struct.tin*

```tin
// A struct type: a name for a group of named fields.
type Book = { title: string, author: string, pages: int }

fn main() {
  let book = Book { title: "Dune", author: "Frank Herbert", pages: 412 }
  print(book.title)
  print("{book.title} has {book.pages} pages")
  print(book)                     // every value can be printed
}
```

<!-- output -->
```text
Dune
Dune has 412 pages
Book { title: "Dune", author: "Frank Herbert", pages: 412 }
```

When a variable has the same name as the field, you can write it once:

*shorthand.tin · tin run shorthand.tin*

```tin
type Point = { x: int, y: int }

fn main() {
  let x = 3
  let y = 4
  let p = Point { x, y }          // same as Point { x: x, y: y }
  print(p)
}
```

<!-- output -->
```text
Point { x: 3, y: 4 }
```

Every field must be given. There are no fields that are silently left empty:

*missing-field.tin · tin check missing-field.tin*

```tin
type Point = { x: int, y: int }

fn main() {
  let p = Point { x: 1 }
}
```

<!-- compiler output -->
```text
error: missing field 'y' in Point
 --> missing-field.tin:4:11
  |
4 |   let p = Point { x: 1 }
  |           ^^^^^^^^^^^^^^
  = note: every field needs a value: y: int
  = fix: add y: 0
```

## Changing fields

Like any value, a struct can change only if it lives in a `var`.

*change.tin · tin run change.tin*

```tin
type Player = { name: string, score: int }

fn main() {
  var player = Player { name: "Ada", score: 0 }
  player.score += 10              // a var's fields can change
  player.name = "Ada L."
  print(player)
}
```

<!-- output -->
```text
Player { name: "Ada L.", score: 10 }
```

## Structs inside structs

A field can have any type, including another struct. Reach into it with more dots.

*nested.tin · tin run nested.tin*

```tin
type Point = { x: float, y: float }
type Line = { from: Point, to: Point }

fn length(l: Line): float {
  let dx = l.to.x - l.from.x
  let dy = l.to.y - l.from.y
  sqrt(dx * dx + dy * dy)
}

fn main() {
  let line = Line { from: Point { x: 0.0, y: 0.0 }, to: Point { x: 3.0, y: 4.0 } }
  print(length(line))
}
```

<!-- output -->
```text
5.0
```

## Methods

A method is a function written as `fn Type.name`. Its first parameter is the value before the dot,
so `r.area()` calls `Rect.area` with `r`. Tin has no classes and no
inheritance: a type is its fields, and methods are ordinary functions you can declare anywhere.

*methods.tin · tin run methods.tin*

```tin
type Rect = { width: float, height: float }

// fn Type.name(...) is a method: the first parameter is the value before the dot.
fn Rect.area(r: Rect): float => r.width * r.height
fn Rect.isSquare(r: Rect): bool => r.width == r.height
fn Rect.scaled(r: Rect, by: float): Rect => Rect { width: r.width * by, height: r.height * by }

fn main() {
  let r = Rect { width: 2.0, height: 3.0 }
  print(r.area())
  print(r.isSquare())
  print(r.scaled(2.0).area())     // methods chain
}
```

<!-- output -->
```text
6.0
false
24.0
```

These methods return new values instead of changing `r`. A method that changes its
value in place uses `inout`, which has its own chapter:
[Values, var and inout](https://tin.ad/docs/learn/values-not-references/).

## Comparing structs

`==` compares structs field by field. Two values with the same fields are equal, wherever they came from.

*equality.tin · tin run equality.tin*

```tin
type Point = { x: int, y: int }

fn main() {
  let a = Point { x: 1, y: 2 }
  let b = Point { x: 1, y: 2 }
  print(a == b)                   // equal when every field is equal
  print(a == Point { x: 2, y: 1 })
}
```

<!-- output -->
```text
true
false
```

## Tuples: a struct without a name

For two or three values that belong together for a moment, such as a function that returns two results, a
tuple saves declaring a type.

*tuples.tin · tin run tuples.tin*

```tin
// A tuple groups a few values without declaring a type.
fn minMax(a: int, b: int): (int, int) {
  if a < b { (a, b) } else { (b, a) }
}

fn main() {
  let pair = minMax(9, 4)
  print(pair)
  print(pair.0)                   // items by position: .0, .1, ...
  let (low, high) = minMax(9, 4)  // or name them all at once
  print("{low} to {high}")
}
```

<!-- output -->
```text
(4, 9)
4
4 to 9
```

If you find yourself writing `.0` and `.1` all over the place, give the fields names
with a struct instead.

## Tasks

### Task 1: Perimeter

Add a method `Rect.perimeter` and print it for a 2.5 by 4.0 rectangle (`13.0`).

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```tin
type Rect = { width: float, height: float }

fn Rect.perimeter(r: Rect): float => 2.0 * (r.width + r.height)

fn main() {
  let r = Rect { width: 2.5, height: 4.0 }
  print(r.perimeter())
}
```

<!-- output -->
```text
13.0
```

### Task 2: How far is the shop?

Write a method so that `home.distanceTo(shop)` works for two `Point`s, and print the
distance from (1, 1) to (4, 5). `sqrt` is built in.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```tin
type Point = { x: float, y: float }

fn Point.distanceTo(a: Point, b: Point): float {
  let dx = b.x - a.x
  let dy = b.y - a.y
  sqrt(dx * dx + dy * dy)
}

fn main() {
  let home = Point { x: 1.0, y: 1.0 }
  let shop = Point { x: 4.0, y: 5.0 }
  print(home.distanceTo(shop))
}
```

<!-- output -->
```text
5.0
```

### Task 3: Adding money · harder

Model money as `{ euros: int, cents: int }` and write `Money.plus`. 3.80 plus 4.50
must print `8.30`, with the cents carried into the euros. Hint: `s.padLeft(2, "0")`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```tin
type Money = { euros: int, cents: int }

fn Money.plus(a: Money, b: Money): Money {
  let total = (a.euros + b.euros) * 100 + a.cents + b.cents
  Money { euros: total / 100, cents: total % 100 }
}

fn main() {
  let coffee = Money { euros: 3, cents: 80 }
  let cake = Money { euros: 4, cents: 50 }
  let bill = coffee.plus(cake)
  print("{bill.euros}.{"{bill.cents}".padLeft(2, "0")}")
}
```

<!-- output -->
```text
8.30
```

Working in whole cents and splitting at the end avoids floating-point rounding. That is
why real money code is usually written this way.

## Recap

- A `type` with fields is a struct; methods take `self`.
- Structs compare with `==` field by field.
- A tuple is a struct without names.

In the reference: [Structs](https://tin.ad/docs/ref/language/#structs) · [Types](https://tin.ad/docs/ref/language/#types)
