diff --git a/vlib/v/tests/generics/generics_str_intp_test.v b/vlib/v/tests/generics/generics_str_intp_test.v new file mode 100644 index 00000000000000..856da3f9341912 --- /dev/null +++ b/vlib/v/tests/generics/generics_str_intp_test.v @@ -0,0 +1,27 @@ +module main + +import strings + +pub struct MyStruct[T] { +pub mut: + result T +} + +pub fn (it MyStruct[T]) indent_str[T]() string { + mut res := strings.new_builder(32) + res.write_string('${it.result}') + return res.str() +} + +fn test_generics_str_intp() { + x := MyStruct[int]{ + result: 100 + } + + y := MyStruct[string]{ + result: 'hello' + } + + assert x.indent_str() == '100' + assert y.indent_str() == 'hello' +} diff --git a/vlib/v/transformer/transformer.v b/vlib/v/transformer/transformer.v index c1ccad453de9c5..73b6e536e2f32c 100644 --- a/vlib/v/transformer/transformer.v +++ b/vlib/v/transformer/transformer.v @@ -1268,6 +1268,11 @@ pub fn (mut t Transformer) simplify_nested_interpolation_in_sb(mut onode ast.Stm return false } original := nexpr.args[0].expr as ast.StringInterLiteral + if original.exprs.len != original.expr_types.len { + // This should be a generic type, e.g., `${it}` where `it` is type of T + // first time, `T` maybe `int`, but second time, `T` maybe `string` + return false + } // only very simple string interpolations, without any formatting, like the following examples // can be optimised to a list of simpler string builder calls, instead of using str_intp: // >> sb.write_string('abc ${num}')