<!-- Values and types · Tin · https://tin.ad/docs/learn/values/ · generated from the built page -->

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

# Values and types

**Goal.** Name values, pick between `let` and `var`, and use Tin's basic types.

## Naming values: let and var

`let` gives a value a name for good. `var` makes a variable you can change later.
Start with `let`; switch to `var` when you really need to change something.

*let-var.tin · tin run let-var.tin*

```tin
fn main() {
  let name = "Tin"       // let: this name always means this value
  var score = 10         // var: this one can change
  score = score + 5
  score += 1
  print("{name} scored {score}")
}
```

<!-- output -->
```text
Tin scored 16
```

`score += 1` is short for `score = score + 1`. Changing a `let` is an error,
and the compiler tells you the fix:

*let-reassign.tin · tin check let-reassign.tin*

```tin
fn main() {
  let score = 10
  score = 11
}
```

<!-- compiler output -->
```text
error: 'score' is immutable
 --> let-reassign.tin:3:3
  |
3 |   score = 11
  |   ^^^^^
  = note: declare it with `var score = ...` to allow reassignment
  = fix: declare score with var
```

Lines marked `fix:` are edits the compiler can make for you. Run `tin fix file.tin`
and it changes `let` to `var`.

## The basic types

Every value has a type. You rarely need to write it: Tin works it out from the value. That is called
type inference.

*types.tin · tin run types.tin*

```tin
fn main() {
  let year = 2026          // int: a whole number
  let price = 4.5          // float: a number with a fractional part
  let open = true          // bool: true or false
  let city = "Lisbon"      // string: text
  print("{year} {price} {open} {city}")

  let count: int = 3       // you can write the type when it helps a reader
  let ratio: float = 2     // a whole-number literal can be a float
  print("{count} {ratio}")
}
```

<!-- output -->
```text
2026 4.5 true Lisbon
3 2.0
```

Once a name has a type, it keeps it. Putting a value of another type in it is an error, caught before the
program runs:

*wrong-type.tin · tin check wrong-type.tin*

```tin
fn main() {
  let count: int = 2.5
}
```

<!-- compiler output -->
```text
error: expected int, found float
 --> wrong-type.tin:2:20
  |
2 |   let count: int = 2.5
  |                    ^^^
  = note: convert with int(x)
  = fix: wrap it in int(...)
```

## Numbers

There are two everyday number types: `int` for whole numbers and `float` for numbers
with a fraction. Dividing two ints gives an int.

*numbers.tin · tin run numbers.tin*

```tin
fn main() {
  print(7 / 2)              // int / int is integer division
  print(7 % 2)              // the remainder
  print(7.0 / 2.0)
  let n = 7
  print(float(n) / 2)       // convert first to get a fraction
  print(int(3.9))           // int() drops the fraction
  print((2.0 / 3.0).fixed(2))
}
```

<!-- output -->
```text
3
1
3.5
3.5
3
0.67
```

Tin never mixes them silently. Multiplying an `int` by a `float` is an error until you say
which one you mean. This seems strict at first, but it is also why Tin never rounds your numbers without you noticing.

*no-mixing.tin · tin check no-mixing.tin*

```tin
fn main() {
  let items = 3
  let price = 4.5
  print(items * price)
}
```

<!-- compiler output -->
```text
error: '*' needs both sides to have the same type, found int and float
 --> no-mixing.tin:4:9
  |
4 |   print(items * price)
  |         ^^^^^^^^^^^^^
  = note: Tin never converts numbers silently: use float(x) or int(x)
  = fix: wrap it in float(...)
```

### How big can an int be?

An `int` is 32 bits: it goes up to 2,147,483,647. Going past that doesn't wrap around to a
negative number like in C, and it doesn't quietly turn into a float like in JavaScript. The program stops with a
*panic*, an error at run time:

*overflow.tin · tin run overflow.tin*

```tin
fn main() {
  var big = 2147483647      // the largest int
  print("about to add one")
  print(big + 1)
}
```

<!-- output -->
```text
about to add one
panic: integer overflow
```

For bigger whole numbers, such as byte counts or timestamps in nanoseconds, use `i64`. You create one
with `i64(…)`, and it never mixes with `int` either:

*i64.tin · tin run i64.tin*

```tin
fn main() {
  let big = i64(2147483647) + i64(1)
  print(big)
  let bytes = i64(3) * i64(1024) * i64(1024) * i64(1024)
  print("3 GiB is {bytes} bytes")
}
```

<!-- output -->
```text
2147483648
3 GiB is 3221225472 bytes
```

## Strings

Strings hold text. `+` joins two strings, and methods are called with a dot.

*strings.tin · tin run strings.tin*

```tin
fn main() {
  let word = "tin"
  print(word.upper())
  print(word + " can")                // + joins two strings
  print("{word} has {word.len} letters")
  print("  spaced  ".trim())
  print("a,b,c".split(","))
  print("ha".repeat(3))
  print(word.contains("in"))
}
```

<!-- output -->
```text
TIN
tin can
tin has 3 letters
spaced
["a", "b", "c"]
hahaha
true
```

`len` counts bytes, not letters. For plain English text they are the same, but
`"é".len` is 2. Keep this in mind when you work with text in other languages.

A hole can say how to format its value after a colon: `{price:.2}` for 2 decimals,
`{n:>4}` for a width of 4, `{n:04}` to pad with zeros:

*format.tin · tin run format.tin*

```tin
fn main() {
  let price = 3.14159
  print("price: {price:.2}")               // 2 decimals
  print("[{7:>4}] [{7:04}] [{"ok":<4}]")   // a width, zeros, left-aligned
  let rows = [("tea", 2.5), ("coffee", 13.0)]
  for r in rows {
    print("{r.0:<8}{r.1:>7.2}")            // a little table
  }
}
```

<!-- output -->
```text
price: 3.14
[   7] [0007] [ok  ]
tea        2.50
coffee    13.00
```

When you need the characters themselves, `s.chars()` gives them as `char` values. A
`char` is one character in single quotes; text in double quotes is always a string:

*chars.tin · tin run chars.tin*

```tin
fn main() {
  let word = "héllo"
  print(word.len)                          // 6 bytes: é takes two
  let letters = word.chars()               // the characters, as char values
  print(letters.len)                       // 5 characters
  print(letters)
  let first = letters[0]                   // a char is written in single quotes: 'h'
  print(first == 'h')
  print(first.upper())
  print(int('A'))                          // its code point
  print(char(66))
}
```

<!-- output -->
```text
6
5
['h', 'é', 'l', 'l', 'o']
true
H
65
B
```

*char-vs-string.tin · tin check char-vs-string.tin*

```tin
fn main() {
  let first = "hello".chars()[0]
  print(first == "h")
}
```

<!-- compiler output -->
```text
error: '==' compares a char with a string
 --> char-vs-string.tin:3:9
  |
3 |   print(first == "h")
  |         ^^^^^^^^^^^^
  = note: a char is written in single quotes: 'a'; or turn the char into text with str(c)
  = fix: use the char 'h'
```

  A char and a string are different types. The fix writes 'h'.

## True or false

A `bool` is `true` or `false`. Comparisons produce one, and
`&&` (and), `||` (or) and `!` (not) combine them.

*bools.tin · tin run bools.tin*

```tin
fn main() {
  let age = 20
  let member = false
  print(age >= 18)
  print(age >= 18 && member)     // and
  print(age >= 18 || member)     // or
  print(!member)                 // not
  print("tin" == "tin")
}
```

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

## Tasks

### Task 1: Celsius to Fahrenheit

Store a temperature in Celsius, say `21.5`, and print it in Fahrenheit
(`F = C × 9 / 5 + 32`) as `21.5 C is 70.7 F`.

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

**Solution

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

```tin
fn main() {
  let celsius = 21.5
  let fahrenheit = celsius * 9 / 5 + 32
  print("{celsius} C is {fahrenheit} F")
}
```

<!-- output -->
```text
21.5 C is 70.7 F
```

### Task 2: Pay for the apples

This doesn't compile. Make it print `Total: 1.20`, with exactly two digits after the point.
Hint: `x.fixed(2)` gives a string with two decimals.

*task-2.tin · tin check task-2.tin*

```tin
fn main() {
  let apples = 3
  let pricePerApple = 0.4
  print("Total: {apples * pricePerApple}")
}
```

<!-- compiler output -->
```text
error: '*' needs both sides to have the same type, found int and float
 --> task-2.tin:4:18
  |
4 |   print("Total: {apples * pricePerApple}")
  |                  ^^^^^^^^^^^^^^^^^^^^^^
  = note: Tin never converts numbers silently: use float(x) or int(x)
  = fix: wrap it in float(...)
```

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

**Solution

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

```tin
fn main() {
  let apples = 3
  let pricePerApple = 0.4
  print("Total: {(float(apples) * pricePerApple).fixed(2)}")
}
```

<!-- output -->
```text
Total: 1.20
```

### Task 3: Seconds to hours, minutes and seconds

Turn `100000` seconds into `100000s is 27h 46m 40s` using only `int`
arithmetic: `/` and `%`.

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

**Solution

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

```tin
fn main() {
  let seconds = 100000
  let hours = seconds / 3600
  let minutes = seconds % 3600 / 60
  let rest = seconds % 60
  print("{seconds}s is {hours}h {minutes}m {rest}s")
}
```

<!-- output -->
```text
100000s is 27h 46m 40s
```

## Recap

- `let` never changes; `var` can be reassigned.
- Types are inferred, so you rarely write them.
- `int`, `float`, `string` and `bool` never mix silently.

In the reference: [Variables and values](https://tin.ad/docs/ref/language/#variables) · [Numbers](https://tin.ad/docs/ref/language/#numbers) · [Strings](https://tin.ad/docs/ref/language/#strings) · [String functions](https://tin.ad/docs/ref/stdlib/#built-in)
