Compile time example III

Published .. 20-06-2024
Type ....... article
Tags ....... v

There are no default arguments in V.

But if I was not using generics, I could have used Trailing struct literal arguments / @[params]

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

struct Address {
    city string
}


fn print_properties[T](data T) {
    print_properties_sub(data,0)
}

fn print_properties_sub[T](data T, level int) {
    println('[${level}] Properties of $T.name:')
    $for field in T.fields { // compile time loop
        if field.attrs.len == 0 || !field.attrs.contains('skip') {
            value:=data.$(field.name)
            if field.is_struct {
                print_properties_sub(value,level+1)
            } else {
                typename:=typeof(value).name
                println('[${level}] ${field.name} (type:${field.typ} ${typename}): ${value}')
            }
        }
    }
}

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

    print_properties(e)
}