From b19052949f9740c804a18c05c1675d034c2284a1 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Wed, 8 Mar 2023 16:54:00 -0300 Subject: [PATCH] cgen: fix array initialization with options (#17562) --- vlib/v/gen/c/array.v | 6 +++++- vlib/v/tests/option_array_test.v | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/option_array_test.v diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 2f2ba1ec6a..58913b2da9 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -51,7 +51,11 @@ fn (mut g Gen) array_init(node ast.ArrayInit, var_name string) { g.expr(expr) g.write(')') } else { - g.expr_with_cast(expr, node.expr_types[i], node.elem_type) + if node.elem_type.has_flag(.option) { + g.expr_with_opt(expr, node.expr_types[i], node.elem_type) + } else { + g.expr_with_cast(expr, node.expr_types[i], node.elem_type) + } } if i != len - 1 { if i > 0 && i & 7 == 0 { // i > 0 && i % 8 == 0 diff --git a/vlib/v/tests/option_array_test.v b/vlib/v/tests/option_array_test.v new file mode 100644 index 0000000000..4fcb2c8d00 --- /dev/null +++ b/vlib/v/tests/option_array_test.v @@ -0,0 +1,11 @@ +fn test_main() { + a := [?int(1), 0, 2] + mut t := a[0] + assert t? == 1 + t = a[1] + assert t? == 0 + t = a[2] + assert t? == 2 + + _ := [?int(none), none] +}