diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 6f24e11518de4b..d1735000ab0a06 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -3070,7 +3070,17 @@ fn (mut g Gen) gen_clone_assignment(var_type ast.Type, val ast.Expr, typ ast.Typ if typ.share() == .shared_t { g.write('(${shared_styp}*)__dup_shared_array(&(${shared_styp}){.mtx = {0}, .val =') } - g.write(' array_clone_static_to_depth(') + is_sumtype := g.table.type_kind(var_type) == .sum_type + if is_sumtype { + variant_typ := g.typ(typ).replace('*', '') + fn_name := g.get_sumtype_casting_fn(typ, var_type) + g.write('${fn_name}(ADDR(${variant_typ}, array_clone_static_to_depth(') + if typ.is_ptr() { + g.write('*') + } + } else { + g.write(' array_clone_static_to_depth(') + } g.expr(val) if typ.share() == .shared_t { g.write('->val') @@ -3081,6 +3091,9 @@ fn (mut g Gen) gen_clone_assignment(var_type ast.Type, val ast.Expr, typ ast.Typ if typ.share() == .shared_t { g.write('}, sizeof(${shared_styp}))') } + if is_sumtype { + g.write('))') + } } else if right_sym.kind == .string { // `str1 = str2` => `str1 = str2.clone()` if var_type.has_flag(.option) { diff --git a/vlib/v/tests/sumtypes/sumtype_map_set_test.v b/vlib/v/tests/sumtypes/sumtype_map_set_test.v new file mode 100644 index 00000000000000..7c266ad0c2e874 --- /dev/null +++ b/vlib/v/tests/sumtypes/sumtype_map_set_test.v @@ -0,0 +1,29 @@ +module main + +pub type Value = f64 | []Value + +fn test_no_ref() { + mut m := map[string]Value{} + var := Value([Value(1.0), Value(2.0), Value(3.0)]) + arr := (var as []Value) + m['var'] = arr + dump(m) + if item := m['var'] { + assert (item as []Value)[1] == Value(2.0) + } else { + assert false + } +} + +fn test_ref() { + mut m := map[string]Value{} + var := Value([Value(1.0), Value(2.0), Value(3.0)]) + arr := &(var as []Value) + m['var'] = arr + dump(m) + if item := m['var'] { + assert (item as []Value)[1] == Value(2.0) + } else { + assert false + } +}