From ef562c92a5f7a45820e38093d7f6f626804b8a26 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 18 Jan 2022 22:16:15 +0800 Subject: [PATCH] cgen: fix assigning a new value to the mut sumtype receiver (#13204) --- vlib/v/gen/c/assign.v | 7 ++++++- vlib/v/tests/mut_receiver_of_sumtype_test.v | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/mut_receiver_of_sumtype_test.v diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index 1890d2db3f..4dc8c862a5 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -435,7 +435,12 @@ fn (mut g Gen) gen_assign_stmt(node ast.AssignStmt) { if op_overloaded { g.op_arg(val, op_expected_right, val_type) } else { - g.expr_with_cast(val, val_type, var_type) + exp_type := if left.is_auto_deref_var() { + var_type.deref() + } else { + var_type + } + g.expr_with_cast(val, val_type, exp_type) } } } diff --git a/vlib/v/tests/mut_receiver_of_sumtype_test.v b/vlib/v/tests/mut_receiver_of_sumtype_test.v new file mode 100644 index 0000000000..0464efc5c4 --- /dev/null +++ b/vlib/v/tests/mut_receiver_of_sumtype_test.v @@ -0,0 +1,17 @@ +pub type Foo = Bar | Baz + +fn (mut f Foo) set_baz() { + f = Baz{} +} + +pub struct Bar {} + +pub struct Baz {} + +fn test_mut_receiver_of_sumtype() { + mut x := Foo(Bar{}) + x.set_baz() + + println(x) + assert '$x' == 'Foo(Baz{})' +}