thp-web/md/learn/functions/parameters.md

74 lines
1.3 KiB
Markdown
Raw Normal View History

2023-09-15 03:15:35 +00:00
# Function parameters
## Immutable reference
```thp
fun add_25(Array[Int] numbers) {
numbers.push(25) // Error: `numbers` is immutable
}
```
When using a regular type as a parameter, only it's immutable
2024-02-20 10:17:21 +00:00
properties can be used
2023-09-15 03:15:35 +00:00
```thp
fun count(Array[Int] numbers) -> Int {
2024-02-20 10:17:21 +00:00
val items_count = numbers.size() // Ok, `size` is pure
2023-09-15 03:15:35 +00:00
items_count
}
```
2024-02-20 10:17:21 +00:00
To use immutable properties you must use a mutable reference.
2023-09-15 03:15:35 +00:00
## Mutable reference
```thp
2024-01-01 14:11:41 +00:00
fun push_25(mut Array[Int] numbers) {
2023-09-15 03:15:35 +00:00
numbers.push(25) // Ok, will also mutate the original array
}
```
2024-01-01 14:11:41 +00:00
Placing a `mut` before the type makes the parameter a mutable
2023-09-15 03:15:35 +00:00
reference. Mutable methods can be used, and the original
2023-10-02 01:41:38 +00:00
data **can** be mutated.
2023-09-15 03:15:35 +00:00
2024-01-01 14:11:41 +00:00
The caller *must* also use `mut`.
2023-09-15 03:15:35 +00:00
```thp
2024-02-20 10:17:21 +00:00
val numbers = Array(0, 1, 2, 3)
2023-09-15 03:15:35 +00:00
2024-01-01 14:11:41 +00:00
push_25(mut numbers) // Pass `numbers` as reference.
2023-09-15 03:15:35 +00:00
print(numbers(4)) // `Some(25)`
```
## Clone
```thp
fun add_25(clone Array[Int] numbers) {
numbers.push(25) // Ok, the original array is unaffected
}
```
Using the `clone` keyword before the type creates a mutable copy
2023-10-02 01:41:38 +00:00
of the parameter (CoW). The original data will **not** be mutated.
2023-09-15 03:15:35 +00:00
```thp
2024-02-20 10:17:21 +00:00
val numbers = Array(1, 2, 3, 4)
2023-09-15 03:15:35 +00:00
2024-01-01 14:11:41 +00:00
add_25(clone numbers) // Pass `numbers` as clone.
2023-09-15 03:15:35 +00:00
print(numbers(4)) // None
```