v2 / vlib / v / tests / comptime / comptime_ref_arg_test.v
101 lines · 88 sloc · 1.66 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1// Declare structures covering a subset of a HAR file
2
3struct HarContent {
4 size i64
5 mime_type string @[json: 'mimeType']
6}
7
8struct HarResponse {
9 content HarContent
10}
11
12struct HarEntry {
13 response HarResponse
14}
15
16pub struct HarLog {
17 entries []HarEntry
18}
19
20struct Har {
21 log HarLog
22}
23
24// Declare function printing object contents using generics
25
26fn show[T](val T) {
27 $if T is string {
28 show_string(val)
29 } $else $if T is $array {
30 show_array(val)
31 } $else $if T is $struct {
32 show_struct(&val)
33 } $else {
34 print('primitive: ${val.str()}')
35 }
36}
37
38fn show_array[T](array []T) {
39 println('array []${T.name}')
40 for i, item in array {
41 println('item ${i}')
42 show(item)
43 println('')
44 }
45}
46
47fn show_struct[T](object &T) {
48 println('struct ${T.name}')
49 $for field in T.fields {
50 mut json_name := field.name
51 for attr in field.attrs {
52 if attr.starts_with('json: ') {
53 json_name = attr[6..]
54 }
55 }
56
57 print('key: ')
58 show_string(json_name)
59 println('')
60
61 println('value ${T.name}.${field.name} (json: ${json_name}), field.typ: ${field.typ}')
62 $if field.typ is string {
63 print('string: ')
64 show_string(object.$(field.name))
65 } $else $if field.is_array {
66 show_array(object.$(field.name))
67 } $else $if field.is_struct {
68 item := object.$(field.name)
69 show_struct(&item)
70 } $else {
71 print('primitive: ')
72 print(object.$(field.name).str())
73 }
74 println('')
75 }
76}
77
78fn show_string(s string) {
79 print(`"`)
80 print(s)
81 print(`"`)
82}
83
84fn test_main() {
85 har := Har{
86 log: HarLog{
87 entries: [
88 HarEntry{
89 response: HarResponse{
90 content: HarContent{
91 size: 48752
92 mime_type: 'text/html'
93 }
94 }
95 },
96 ]
97 }
98 }
99 show(har)
100 assert true
101}
102