| 1 | module main |
| 2 | |
| 3 | import strings |
| 4 | |
| 5 | pub struct MyStruct[T] { |
| 6 | pub mut: |
| 7 | result T |
| 8 | } |
| 9 | |
| 10 | pub 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 | |
| 16 | fn 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 | |
| 29 | struct Foo[T] { |
| 30 | bar T |
| 31 | } |
| 32 | |
| 33 | fn (b Foo[T]) str() string { |
| 34 | return '${b.bar:b}/${b.bar:o}/${b.bar:d}/${b.bar:x}' |
| 35 | } |
| 36 | |
| 37 | fn generic_int_format[T](value T) string { |
| 38 | return '${value:b}/${value:o}/${value:d}/${value:x}' |
| 39 | } |
| 40 | |
| 41 | fn generic_int_padded_format[T](value T) string { |
| 42 | return '${value:08x}/${value:+d}' |
| 43 | } |
| 44 | |
| 45 | // vfmt off |
| 46 | fn generic_default_format[T](value T) string { |
| 47 | return '${value:_}' |
| 48 | } |
| 49 | // vfmt on |
| 50 | |
| 51 | fn 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 | |