Compile-time reflection

Having built-in JSON support is nice, but V also allows you to create efficient serializers for any data format. V has compile-time if and for constructs:

  1. // TODO: not fully implemented
  2. struct User {
  3. name string
  4. age int
  5. }
  6. // Note: T should be passed a struct name only
  7. fn decode<T>(data string) T {
  8. mut result := T{}
  9. // compile-time `for` loop
  10. // T.fields gives an array of a field metadata type
  11. $for field in T.fields {
  12. $if field.typ is string {
  13. // $(string_expr) produces an identifier
  14. result.$(field.name) = get_string(data, field.name)
  15. } $else $if field.typ is int {
  16. result.$(field.name) = get_int(data, field.name)
  17. }
  18. }
  19. return result
  20. }
  21. // `decode<User>` generates:
  22. fn decode_User(data string) User {
  23. mut result := User{}
  24. result.name = get_string(data, 'name')
  25. result.age = get_int(data, 'age')
  26. return result
  27. }