diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index 1204a4ae7bfa10..cb055344df7fa3 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -157,6 +157,18 @@ fn (mut g Gen) expr_with_opt(expr ast.Expr, expr_typ ast.Type, ret_typ ast.Type) return '' } +fn (mut g Gen) expr_with_fixed_array_opt(expr ast.Expr, expr_typ ast.Type, ret_typ ast.Type) { + tmp_var := g.new_tmp_var() + stmt_str := g.go_before_last_stmt().trim_space() + styp := g.styp(expr_typ) + g.empty_line = true + g.writeln('${styp} ${tmp_var} = {.state = 0};') + g.write('memcpy(${tmp_var}.data, ') + g.expr(expr) + g.writeln(', sizeof(${g.styp(ret_typ)}));') + g.write2(stmt_str, tmp_var) +} + fn (mut g Gen) assign_stmt(node_ ast.AssignStmt) { mut node := unsafe { node_ } if node.is_static { diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 5934f649514c0c..f17ab3f37afe6d 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -692,9 +692,15 @@ fn (mut g Gen) struct_init_field(sfield ast.StructInitField, language ast.Langua field_unwrap_sym.info.elem_type, field_unwrap_sym.info.size) } ast.CastExpr, ast.CallExpr { - tmp_var := g.expr_with_var(sfield.expr, sfield.expected_type, false) - g.fixed_array_var_init(tmp_var, false, field_unwrap_sym.info.elem_type, - field_unwrap_sym.info.size) + if sfield.expected_type.has_flag(.option) && !field_unwrap_typ.has_flag(.option) { + g.expr_with_fixed_array_opt(sfield.expr, sfield.expected_type, + field_unwrap_typ) + } else { + tmp_var := g.expr_with_var(sfield.expr, sfield.expected_type, + false) + g.fixed_array_var_init(tmp_var, false, field_unwrap_sym.info.elem_type, + field_unwrap_sym.info.size) + } } ast.ArrayInit { if sfield.expr.has_index { diff --git a/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v b/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v new file mode 100644 index 00000000000000..9c9fd75ed56e21 --- /dev/null +++ b/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v @@ -0,0 +1,15 @@ +type Arr = [4]u8 + +struct Foo { + bar int + baz ?Arr +} + +fn test_struct_field_init_with_fixed_array_opt() { + f := Foo{ + bar: 1 + baz: Arr([u8(5), 4, 3, 2]!) + } + println(f) + assert f.baz as Arr == [u8(5), 4, 3, 2]! +}