Learn Tin · Part 1: The language · Chapter 5
Structs and methods
Group values into a type and give it methods.
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.
tin run struct.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
} 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:
tin run shorthand.tintype 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)
} Point { x: 3, y: 4 } Every field must be given. There are no fields that are silently left empty:
tin check missing-field.tintype Point = { x: int, y: int }
fn main() {
let p = Point { x: 1 }
} 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.
tin run change.tintype 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)
} Player { name: "Ada L.", score: 10 } Structs inside structs
A field can have any type, including another struct. Reach into it with more dots.
tin run nested.tintype 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))
} 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.
tin run methods.tintype 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
} 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.
Comparing structs
== compares structs field by field. Two values with the same fields are equal, wherever they came from.
tin run equality.tintype 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 })
} 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.
tin run tuples.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}")
} (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).
Solution
tin run task-1.solution.tintype 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())
} 13.0 ●●○ Task 2: How far is the shop?
Write a method so that home.distanceTo(shop) works for two Points, and print the
distance from (1, 1) to (4, 5). sqrt is built in.
Solution
tin run task-2.solution.tintype 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))
} 5.0 ●●● Task 3: Adding money
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").
Solution
tin run task-3.solution.tintype 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")}")
} 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.
What's next
Next: Sum types and match. A value that is one of several shapes, and a match that handles every one.