vxx / vlib / v / tests / generics / generics_str_intp_test.v
66 lines · 52 sloc · 1.2 KB · 927a1e258e7706e68b54de201e5d2dc6182e545d
Raw
1module main
2
3import strings
4
5pub struct MyStruct[T] {
6pub mut:
7 result T
8}
9
10pub fn (it MyStruct[T]) indent_str[T]() string {
11 mut res := strings.new_builder(32)
12 res.write_string('${it.result}')
13 return res.str()
14}
15
16fn test_generics_str_intp() {
17 x := MyStruct[int]{
18 result: 100
19 }
20
21 y := MyStruct[string]{
22 result: 'hello'
23 }
24
25 assert x.indent_str() == '100'
26 assert y.indent_str() == 'hello'
27}
28
29struct Foo[T] {
30 bar T
31}
32
33fn (b Foo[T]) str() string {
34 return '${b.bar:b}/${b.bar:o}/${b.bar:d}/${b.bar:x}'
35}
36
37fn generic_int_format[T](value T) string {
38 return '${value:b}/${value:o}/${value:d}/${value:x}'
39}
40
41fn generic_int_padded_format[T](value T) string {
42 return '${value:08x}/${value:+d}'
43}
44
45// vfmt off
46fn generic_default_format[T](value T) string {
47 return '${value:_}'
48}
49// vfmt on
50
51fn test_generic_string_interpolation_explicit_int_formats() {
52 assert generic_int_format[int](42) == '101010/52/42/2a'
53 assert generic_int_padded_format[int](42) == '0000002a/+42'
54 assert generic_default_format[int](42) == '42'
55 assert generic_default_format[string]('ok') == 'ok'
56
57 baz := Foo[int]{
58 bar: 42
59 }
60 assert baz.str() == '101010/52/42/2a'
61
62 baz_inferred := Foo{
63 bar: 56
64 }
65 assert baz_inferred.str() == '111000/70/56/38'
66}
67