Compile-Time Code
23.1 Compile-Time $if
OS: windows, linux, macos, freebsd, openbsd, android, ios, termux, solaris, haiku. Compilers: gcc, tinyc, clang, msvc, mingw. Platforms: x64, x32, arm64, arm32, rv64, little_endian, big_endian. Other: debug, prod, test, glibc, prealloc, no_bounds_checking, freestanding, threads, js_node, js_browser.
$if windows {
println('Windows')
} $else $if linux {
println('Linux')
} $else $if macos {
println('macOS')
}
$if debug { println('debug build') } // v -d debug / -g
$if prod { println('production') } // -prod
$if test { println('running tests') }
$if mycustomflag ? { println('custom') } // v -d mycustomflag
$if x64 { } $else $if arm64 { }
$if tinyc { } $if gcc { } $if clang { } $if msvc { }
$if js { } $if wasm32 { }23.2 Compile-Time Reflection
T.fields, T.methods, T.attributes, T.values (enums), T.variants (sum types), field.attrs, field.is_pub, field.is_mut, obj.$(field.name) (dynamic field access), obj.$method() (comptime method call).
These power the built-in JSON encoder, the ORM, and veb.
struct User {
name string
age int
email string
}
fn print_fields[T](obj T) {
$for field in T.fields {
println('${field.name}: ${typeof(obj.$(field.name)).name} = ${obj.$(field.name)}')
$if field.typ is string {
println(' (string field)')
}
}
$for method in T.methods {
println('method: ${method.name}')
}
$for attr in T.attributes { println(attr.name) }
}
fn main() {
print_fields(User{'Ana', 30, '[email protected]'})
}23.3 Compile-Time Pseudo-Variables and Functions
println(@FILE)
println(@LINE)
println(@FN)
println(@METHOD)
println(@MOD)
println(@STRUCT)
println(@VEXE)
println(@VHASH)
println(@VMODROOT)
println(@BUILD_DATE)
println(@BUILD_TIME)
println(@COLUMN)
println(@LOCATION)
embedded := $embed_file('assets/logo.png') // embed a file in the binary
println(embedded.len)
bytes := embedded.to_bytes()
html := $tmpl('templates/index.html') // compile-time template (uses local vars)
api_url := $env('API_URL') // env var at compile time
$compile_error('unsupported platform') // force a compile error
$compile_warn('deprecated config')
key := $d('my_key', 'default') // -d my_key=value compile-time define (newer)23.4 dump() and $dbg
x := 42
dump(x * 2) // prints [file.v:2] x * 2: 84 and returns the value
$dbg // interactive debugger breakpoint (V 0.4.6+): inspect locals