docs: document dump(expr)

pull/9699/head weekly.2021.15
Delyan Angelov 2021-04-12 12:01:29 +03:00
parent 7ba13a415a
commit a4fb851f3d
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
1 changed files with 34 additions and 0 deletions

View File

@ -124,6 +124,7 @@ For more details and troubleshooting, please visit the [vab GitHub repository](h
* [v fmt](#v-fmt)
* [Profiling](#profiling)
* [Advanced Topics](#advanced-topics)
* [Dumping expressions at runtime](#dumping-expressions-at-runtime)
* [Memory-unsafe code](#memory-unsafe-code)
* [Structs with reference fields](#structs-with-reference-fields)
* [sizeof and __offsetof](#sizeof-and-__offsetof)
@ -3284,6 +3285,39 @@ fn main() {
# Advanced Topics
## Dumping expressions at runtime
You can dump/trace the value of any V expression using `dump(expr)`.
For example, save this code sample as `factorial.v`, then run it with
`v run factorial.v`:
```v
fn factorial(n u32) u32 {
if dump(n <= 1) {
return dump(1)
}
return dump(n * factorial(n - 1))
}
fn main() {
println(factorial(5))
}
```
You will get:
```
[factorial.v:2] n <= 1: false
[factorial.v:2] n <= 1: false
[factorial.v:2] n <= 1: false
[factorial.v:2] n <= 1: false
[factorial.v:2] n <= 1: true
[factorial.v:3] 1: 1
[factorial.v:5] n * factorial(n - 1): 2
[factorial.v:5] n * factorial(n - 1): 6
[factorial.v:5] n * factorial(n - 1): 24
[factorial.v:5] n * factorial(n - 1): 120
120
```
Note that `dump(expr)` will trace both the source location,
the expression itself, and the expression value.
## Memory-unsafe code
Sometimes for efficiency you may want to write low-level code that can potentially