From 66c43078972f9f11e4c266c674b20b6ebb7cd747 Mon Sep 17 00:00:00 2001 From: larpon <768942+larpon@users.noreply.github.com> Date: Wed, 26 Jun 2024 16:08:08 +0200 Subject: [PATCH] examples: add `compiletime/d_compile_value.v` (#21738) --- examples/compiletime/d_compile_value.v | 56 ++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 examples/compiletime/d_compile_value.v diff --git a/examples/compiletime/d_compile_value.v b/examples/compiletime/d_compile_value.v new file mode 100644 index 0000000000..765d0060ed --- /dev/null +++ b/examples/compiletime/d_compile_value.v @@ -0,0 +1,56 @@ +// This example shows how to use V's compile time defines and values via the -d flag and $d() function. +// +// To change the default values below, pass compile flags to v using: `-d ident=` +// Examples: +// ยดยดยด +// v -d header -d pad=10 -d jobs=8 run d_compile_value.v +// v -d id="Bob" -d pad=2 -d pad_char='$' -d jobs=10 run d_compile_value.v +// ``` + +const pad = $d('pad', 5) +const pad_char = $d('pad_char', `-`) + +const footer = ' +Available compile time flags: + -d pad= + -d pad_char= + -d id="" + -d jobs= + -d header= +You can turn this message off with: + -d footer=false' + +struct Job { + id string = $d('id', 'Job') // adjust with `-d id="My ID"` +} + +struct App { + jobs [$d('jobs', 4)]Job // adjust fixed array size with `-d jobs=6` +} + +// println_padded prints `str` to stdout with a padding. +// Padding length and padding character can be adjusted at compile time +// via `-d pad=1` and `-d pad_char=x`. +fn println_padded(str string) { + for _ in 0 .. pad { + print(rune(pad_char)) + } + println(' ${str}') +} + +fn main() { + header := $d('header', false) // adjust header variable with `-d header=true` or simply `-d header` + if header { + println_padded('Compile Value Example') + } + + app := App{} + for i, job in app.jobs { + println_padded('${job.id} ${i + 1}') + } + + // Turn the footer message off using `-d footer=false` + if $d('footer', true) { + println(footer) + } +}