diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 36df60b2fb..2e7d874905 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -1166,9 +1166,10 @@ pub: has_default bool has_it bool // true if temp variable it is used pub mut: - expr_types []Type // [Dog, Cat] // also used for interface_types - elem_type Type // element type - typ Type // array type + expr_types []Type // [Dog, Cat] // also used for interface_types + elem_type Type // element type + default_type Type // default value type + typ Type // array type } pub struct ArrayDecompose { diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 8db74f7501..2d95231c08 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -20,6 +20,7 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type { if node.has_default { default_expr := node.default_expr default_typ := c.check_expr_opt_call(default_expr, c.expr(default_expr)) + node.default_type = default_typ c.check_expected(default_typ, node.elem_type) or { c.error(err.msg, default_expr.position()) } diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 9fdef0e60b..7232992835 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -213,7 +213,7 @@ fn (mut g Gen) array_init(node ast.ArrayInit) { g.write('}[0])') } else if node.has_default { g.write('&($elem_styp[]){') - g.expr(node.default_expr) + g.expr_with_cast(node.default_expr, node.default_type, node.elem_type) g.write('})') } else if node.has_len && node.elem_type == ast.string_type { g.write('&($elem_styp[]){') diff --git a/vlib/v/tests/array_of_sumtype_with_default_test.v b/vlib/v/tests/array_of_sumtype_with_default_test.v new file mode 100644 index 0000000000..224bf74db4 --- /dev/null +++ b/vlib/v/tests/array_of_sumtype_with_default_test.v @@ -0,0 +1,11 @@ +type Abc = int | string + +fn test_array_of_sumtype_with_default() { + a1 := []Abc{len: 1, init: 22} + println(a1) + assert '$a1' == '[Abc(22)]' + + a2 := []Abc{len: 1, init: 'hello'} + println(a2) + assert '$a2' == "[Abc('hello')]" +}