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