Learn · The language · 11 of 34
Values, var and inout
Goal. Understand why every value is a copy, and change a caller's variable on purpose with inout.
This chapter is short, but it's the one most different from Python, JavaScript or Java. If you remember one rule from it: in Tin, everything is a value.
Assigning makes a copy
In many languages, b = a for a list makes b a second name for the same list, so
changing one changes "both". In Tin, b gets its own copy:
tin run copy.tinfn main() {
var a = [1, 2]
let b = a // b gets its own copy
a.push(3)
print(a)
print(b) // still [1, 2]
} [1, 2, 3]
[1, 2] Structs work the same way:
tin run copy-struct.tintype Robot = { name: string, battery: int }
fn main() {
var first = Robot { name: "Bud", battery: 90 }
var second = first // a copy, not a second name for the same robot
second.name = "Petal"
second.battery = 40
print(first)
print(second)
} Robot { name: "Bud", battery: 90 }
Robot { name: "Petal", battery: 40 } Functions get copies too
A function receives a copy of each argument, so it can't change the caller's data behind its back. To change something, it returns the new value:
tin run param.tin// A parameter is a copy too. The function can't reach the caller's data.
fn drained(r: Robot): Robot {
var out = r
out.battery = 0
out
}
type Robot = { name: string, battery: int }
fn main() {
let bud = Robot { name: "Bud", battery: 90 }
let empty = drained(bud)
print(bud) // unchanged
print(empty)
} Robot { name: "Bud", battery: 90 }
Robot { name: "Bud", battery: 0 } Parameters are read-only, and the error says what to do instead:
tin check param-let.tintype Robot = { name: string, battery: int }
fn drain(r: Robot) {
r.battery = 0
}
fn main() {
drain(Robot { name: "Bud", battery: 90 })
} error: cannot change this: 'r' is immutable
--> param-let.tin:4:3
|
4 | r.battery = 0
| ^
= note: parameters are read-only; take it as `r: inout Robot` to change the caller's variable inout: when a function should change your variable
Sometimes changing a variable in place is exactly what you want. Mark the parameter inout.
The caller writes &, so whoever reads the call can see that the variable may change there:
tin run inout.tintype Robot = { name: string, battery: int }
// inout: this function may change the caller's variable.
fn charge(r: inout Robot, amount: int) {
r.battery = min(100, r.battery + amount)
}
fn main() {
var bud = Robot { name: "Bud", battery: 70 }
charge(&bud, 20) // & at the call: you can see that bud may change here
print(bud)
charge(&bud, 20)
print(bud)
} Robot { name: "Bud", battery: 90 }
Robot { name: "Bud", battery: 100 } Only a var can be passed this way:
tin check inout-let.tinfn addZero(xs: inout int[]) {
xs.push(0)
}
fn main() {
let fixed = [1, 2]
addZero(&fixed)
} error: cannot call 'addZero', which changes its argument: 'fixed' is immutable
--> inout-let.tin:7:12
|
7 | addZero(&fixed)
| ^^^^^
= note: declare it with `var fixed = ...` to change it
= fix: declare fixed with var A method whose first parameter is inout changes the value it's called on, like
push does for arrays. On a method call you don't write &:
tin run inout-method.tintype Counter = { count: int }
// A method whose first parameter is inout changes the value it is called on.
fn Counter.bump(c: inout Counter) {
c.count += 1
}
fn main() {
var clicks = Counter { count: 0 }
clicks.bump() // a method call on a var needs no &
clicks.bump()
print(clicks.count)
} 2 Your own for loops
inout is also how you make a type that for can walk. Give it a next method that
changes the value and returns Some(item), then None when it is done. The loop works on
its own copy, so your variable is left as it was:
tin run iterator.tintype Countdown = { n: int }
// next changes the countdown in place (inout) and gives the next number, or None when done
fn Countdown.next(c: inout Countdown): Option<int> {
if c.n == 0 { return None }
c.n -= 1
Some(c.n + 1)
}
fn main() {
let launch = Countdown { n: 3 }
for t in launch {
print("{t}...")
}
print("liftoff, and launch.n is still {launch.n}")
} 3...
2...
1...
liftoff, and launch.n is still 3 A collection type can instead have iter, returning something for already
walks, such as an array or a Map: fn Tree.iter(t: Tree): int[].
Why it works this way
- You can trust what you read. If a line doesn't mention
x(or pass&x), it didn't changex. - Agents can't reach into your data. In Part 2, an agent's tools get copies of what you pass them. A model can't change a list you're holding.
- The same program gives the same result. There are no two names for one thing that change in an order you didn't expect.
Today's cost: copies are made right away, so copying a big array in a hot loop costs time. Tin plans to copy only when something actually changes (copy-on-write). Programs will print the same things, only faster.
Tasks
Task 1: Predict the output
Before running it, write down what this prints: var original = ["a", "b"],
var backup = original, original.push("c"), backup[0] = "z", then print
both.
Solution
tin run task-1.solution.tinfn main() {
var original = ["a", "b"]
var backup = original
original.push("c")
backup[0] = "z"
print(original) // ["a", "b", "c"]
print(backup) // ["z", "b"]
} ["a", "b", "c"]
["z", "b"] Task 2: Swap the ends
Write swapEnds(xs: inout int[]) that swaps the first and the last item in place. It should do
nothing for arrays shorter than two.
Solution
tin run task-2.solution.tinfn swapEnds(xs: inout int[]) {
if xs.len < 2 { return }
let first = xs[0]
xs[0] = xs[xs.len - 1]
xs[xs.len - 1] = first
}
fn main() {
var xs = [1, 2, 3, 4]
swapEnds(&xs)
print(xs)
} [4, 2, 3, 1] Task 3: A bank account
Give Account { owner: string, balance: int } two inout methods:
deposit, and withdraw that returns false and changes nothing if the
balance is too low.
Solution
tin run task-3.solution.tintype Account = { owner: string, balance: int }
fn Account.deposit(a: inout Account, amount: int) {
a.balance += amount
}
fn Account.withdraw(a: inout Account, amount: int): bool {
if amount > a.balance { return false }
a.balance -= amount
true
}
fn main() {
var acct = Account { owner: "ada", balance: 0 }
acct.deposit(50)
print(acct.withdraw(80))
print(acct.withdraw(30))
print(acct)
} false
true
Account { owner: "ada", balance: 20 } Recap
- Assigning or passing a value copies it; nothing is shared by accident.
inoutlets a function change the variable you pass.- This is what makes agents and tasks safe to run side by side.
In the reference: Arrays and structs are values · Variables