diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 3f71bcf5f9..143e76a0bf 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -71,11 +71,15 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type { if node.exprs.len > 0 && node.elem_type == ast.void_type { mut expected_value_type := ast.void_type mut expecting_interface_array := false + mut expecting_sumtype_array := false if c.expected_type != 0 { expected_value_type = c.table.value_type(c.expected_type) - if c.table.sym(expected_value_type).kind == .interface_ { + expected_value_sym := c.table.sym(expected_value_type) + if expected_value_sym.kind == .interface_ { // Array of interfaces? (`[dog, cat]`) Save the interface type (`Animal`) expecting_interface_array = true + } else if expected_value_sym.kind == .sum_type { + expecting_sumtype_array = true } } // expecting_interface_array := c.expected_type != 0 && @@ -104,6 +108,11 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type { } } continue + } else if expecting_sumtype_array { + if i == 0 { + elem_type = expected_value_type + } + continue } // The first element's type if i == 0 { diff --git a/vlib/v/tests/array_of_sumtype_init_test.v b/vlib/v/tests/array_of_sumtype_init_test.v new file mode 100644 index 0000000000..6ebd8b5aed --- /dev/null +++ b/vlib/v/tests/array_of_sumtype_init_test.v @@ -0,0 +1,25 @@ +pub type MenuItem = Action | Group | Separater + +pub struct Group { + children []MenuItem +} + +pub struct Separater {} + +pub struct Action {} + +fn test_array_of_sumtype_init() { + g := Group{ + children: [ + Action{}, + Separater{}, + Group{ + children: [ + Action{}, + ] + }, + ] + } + println(g) + assert g.children.len == 3 +}