v / examples / compiletime / d_compile_value.v
56 lines · 48 sloc · 1.37 KB · 66c43078972f9f11e4c266c674b20b6ebb7cd747
Raw
1// This example shows how to use V's compile time defines and values via the -d flag and $d() function.
2//
3// To change the default values below, pass compile flags to v using: `-d ident=<value>`
4// Examples:
5// ´´´
6// v -d header -d pad=10 -d jobs=8 run d_compile_value.v
7// v -d id="Bob" -d pad=2 -d pad_char='$' -d jobs=10 run d_compile_value.v
8// ```
9
10const pad = $d('pad', 5)
11const pad_char = $d('pad_char', `-`)
12
13const footer = '
14Available compile time flags:
15 -d pad=<i64>
16 -d pad_char=<character>
17 -d id="<string>"
18 -d jobs=<i64>
19 -d header=<bool>
20You can turn this message off with:
21 -d footer=false'
22
23struct Job {
24 id string = $d('id', 'Job') // adjust with `-d id="My ID"`
25}
26
27struct App {
28 jobs [$d('jobs', 4)]Job // adjust fixed array size with `-d jobs=6`
29}
30
31// println_padded prints `str` to stdout with a padding.
32// Padding length and padding character can be adjusted at compile time
33// via `-d pad=1` and `-d pad_char=x`.
34fn println_padded(str string) {
35 for _ in 0 .. pad {
36 print(rune(pad_char))
37 }
38 println(' ${str}')
39}
40
41fn main() {
42 header := $d('header', false) // adjust header variable with `-d header=true` or simply `-d header`
43 if header {
44 println_padded('Compile Value Example')
45 }
46
47 app := App{}
48 for i, job in app.jobs {
49 println_padded('${job.id} ${i + 1}')
50 }
51
52 // Turn the footer message off using `-d footer=false`
53 if $d('footer', true) {
54 println(footer)
55 }
56}
57