diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index ecabd48e01..ffde01cce7 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -871,3 +871,9 @@ fn test_mutli_array_index() { b[0][0] = 1 assert '$b' == '[[1, 0, 0], [0, 0, 0]]' } + +fn test_plus_assign_string() { + mut a := [''] + a[0] += 'abc' + assert a == ['abc'] +} diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 3e103f36b9..26ecc709b9 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -1144,9 +1144,17 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) { } mut str_add := false if var_type == table.string_type_idx && assign_stmt.op == .plus_assign { - // str += str2 => `str = string_add(str, str2)` - g.expr(left) - g.write(' = /*f*/string_add(') + if left is ast.IndexExpr { + // a[0] += str => `array_set(&a, 0, &(string[]) {string_add(...))})` + g.expr(left) + g.write('string_add(') + } else { + // str += str2 => `str = string_add(str, str2)` + g.expr(left) + g.write(' = /*f*/string_add(') + } + g.is_assign_lhs = false + g.is_assign_rhs = true str_add = true } if right_sym.kind == .function && is_decl { @@ -1209,11 +1217,12 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) { if unwrap_optional { g.write('.data') } + if str_add { + g.write(')') + } if g.is_array_set { g.write(' })') g.is_array_set = false - } else if str_add { - g.write(')') } } g.right_is_opt = false @@ -2196,7 +2205,8 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) { g.write(', &') } // `x[0] *= y` - if g.assign_op != .assign && g.assign_op in token.assign_tokens { + if g.assign_op != .assign && g.assign_op in token.assign_tokens && + info.elem_type != table.string_type { // TODO move this g.write('*($elem_type_str*)array_get(') if left_is_ptr {