thp-web/md/learn/basics/variables.md

64 lines
1.1 KiB
Markdown
Raw Normal View History

2023-09-15 03:15:35 +00:00
# Variables
2023-10-02 01:41:38 +00:00
thp distinguishes between mutable and immutable variables.
2023-09-15 03:15:35 +00:00
## Immutable variables
2023-09-15 03:15:35 +00:00
Defined with `let`, followed by a variable name and a value.
2023-09-15 03:15:35 +00:00
```thp
let surname = "Doe"
let year_of_birth = 1984
2023-09-15 03:15:35 +00:00
```
2023-10-02 01:41:38 +00:00
### Datatype annotation
2023-09-15 03:15:35 +00:00
Written after the `let` keyword but before the variable name.
2023-09-15 03:15:35 +00:00
```thp
let String surname = "Doe"
let Int year_of_birth = 1984
2023-09-15 03:15:35 +00:00
```
When annotating an immutable variable the `let` keyword is optional
2023-09-15 03:15:35 +00:00
```thp
// Equivalent to the previous code
String surname = "Doe"
Int year_of_birth = 1984
```
2023-09-15 03:15:35 +00:00
This means that if a variable has only a datatype, it is immutable.
2023-09-15 03:15:35 +00:00
## Mutable variables
Defined with `let mut`, followed by a variable name and a value.
2023-09-15 03:15:35 +00:00
```thp
let mut name = "John"
let mut age = 32
2023-09-15 03:15:35 +00:00
```
2023-10-02 01:41:38 +00:00
### Datatype annotation
2023-09-15 03:15:35 +00:00
Written after the `let mut` keywords but before the variable name.
2023-09-15 03:15:35 +00:00
```thp
let mut String name = "John"
let mut Int age = 32
2023-09-15 03:15:35 +00:00
```
When annotating a mutable variable the keyword `let` is optional. `mut` is still **required**.
2023-09-15 03:15:35 +00:00
```thp
2023-10-02 01:41:38 +00:00
// Equivalent to the previous code
mut String name = "John"
mut Int age = 32
2023-09-15 03:15:35 +00:00
```