Compile time example

Published .. 16-07-2024
Type ....... article
Tags ....... v

Like Go's struct tag, you can use attributes in V. But in Go, struct tags are a form of reflection, that is checked for when you program run. In V the attributes can be used at compile time.

This example creates a generic print_properties function which prints all properties of a struct, except those marked with the attributes skip.

struct Employee {
    name   string
    age    int @[skip] 
    salary f64
}


fn print_properties<T>(data T) {
    println('Properties of $T.name:')

    $for field in T.fields { // compile time loop
        if field.attrs.len == 0 || !field.attrs.contains('skip') {
            v:=data.$(field.name)
            println('${field.name}: ${v}')
        }
    }
}

fn main() {
    e := Employee{
        name: 'John Doe',
        age: 30, // This field will not be printed due to [skip] attribute
        salary: 65000.00,
    }
    print_properties(e)
}