diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 0555c731a5..b6ab68d8a0 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -343,9 +343,17 @@ fn (mut g Gen) array_init_with_fields(node ast.ArrayInit, elem_type Type, is_amp g.writeln('; ${ind}++) {') g.write('\t${tmp}[${ind}] = ') if node.has_default { - 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) + } } else { - g.write(g.type_default(node.elem_type)) + if node.elem_type.has_flag(.option) { + g.expr_with_opt(ast.None{}, ast.none_type, node.elem_type) + } else { + g.write(g.type_default(node.elem_type)) + } } g.writeln(';') g.writeln('}') @@ -355,6 +363,10 @@ fn (mut g Gen) array_init_with_fields(node ast.ArrayInit, elem_type Type, is_amp g.write('&(${elem_styp}[]){') 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('&') + g.expr_with_opt(ast.None{}, ast.none_type, node.elem_type) + g.write(')') } else if node.has_len && node.elem_type == ast.string_type { g.write('&(${elem_styp}[]){') g.write('_SLIT("")') diff --git a/vlib/v/tests/check_init_value_for_arrays_of_option_test.v b/vlib/v/tests/check_init_value_for_arrays_of_option_test.v new file mode 100644 index 0000000000..18534917ea --- /dev/null +++ b/vlib/v/tests/check_init_value_for_arrays_of_option_test.v @@ -0,0 +1,59 @@ +fn check_init_value_for_arrays_of_option[T]() { + a := []?T{len: 2} + assert a.len == 2 + for value in a { + assert value == none + println(value) + } +} + +enum MyEnum { + zero + one + two +} + +enum MyEnum32 as u32 { + zero + one + two +} + +struct MyStruct { + x int = 123 + name string = 'abc' +} + +fn test_primitives() { + check_init_value_for_arrays_of_option[i8]() + check_init_value_for_arrays_of_option[i16]() + check_init_value_for_arrays_of_option[i32]() + check_init_value_for_arrays_of_option[int]() + check_init_value_for_arrays_of_option[i64]() + + check_init_value_for_arrays_of_option[u8]() + check_init_value_for_arrays_of_option[byte]() + check_init_value_for_arrays_of_option[u16]() + check_init_value_for_arrays_of_option[u32]() + check_init_value_for_arrays_of_option[u64]() + + check_init_value_for_arrays_of_option[f32]() + check_init_value_for_arrays_of_option[f64]() + + check_init_value_for_arrays_of_option[string]() + check_init_value_for_arrays_of_option[rune]() +} + +fn test_arrays() { + check_init_value_for_arrays_of_option[[]int]() + check_init_value_for_arrays_of_option[[]f32]() +} + +fn test_enums() { + check_init_value_for_arrays_of_option[MyEnum]() + check_init_value_for_arrays_of_option[MyEnum32]() +} + +fn test_structs() { + check_init_value_for_arrays_of_option[MyStruct]() +}