Compile time example II

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

Extended example with struct inside struct.

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

struct Address {
    city string
}


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') {
            value:=data.$(field.name)
            if field.is_struct {
                print_properties(value)
            } else {
                typename:=typeof(value).name
                println('${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)
}