From b4f0bb247d292d57ba3ac28860356911eb6768d3 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Tue, 7 Mar 2023 17:53:07 -0300 Subject: [PATCH] cgen: fix default initialization of option array with none values (#17536) --- vlib/v/gen/c/array.v | 6 +++++- vlib/v/tests/option_array_init_test.v | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/option_array_init_test.v diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index b6ab68d8a0..0198fd1529 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -361,7 +361,11 @@ fn (mut g Gen) array_init_with_fields(node ast.ArrayInit, elem_type Type, is_amp g.write(' (voidptr)${tmp})') } else if node.has_default { g.write('&(${elem_styp}[]){') - g.expr_with_cast(node.default_expr, node.default_type, node.elem_type) + if node.elem_type.has_flag(.option) { + g.expr_with_opt(node.default_expr, node.default_type, node.elem_type) + } else { + g.expr_with_cast(node.default_expr, node.default_type, node.elem_type) + } g.write('})') } else if node.has_len && node.elem_type.has_flag(.option) { g.write('&') diff --git a/vlib/v/tests/option_array_init_test.v b/vlib/v/tests/option_array_init_test.v new file mode 100644 index 0000000000..ccc42b4b26 --- /dev/null +++ b/vlib/v/tests/option_array_init_test.v @@ -0,0 +1,10 @@ +fn test_main() { + a := []?int{len: 3, init: none} + mut t := a[0] + assert t == none + t = a[1] + assert t == none + t = a[2] + assert t == none + assert a.len == 3 +}