From ac1b31dbbae1a4e0876c72063b6ad46feb681d88 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 3 Mar 2022 18:32:55 +0800 Subject: [PATCH] checker: fix error for array of interface init in for_in (#13636) --- vlib/v/checker/containers.v | 5 +++ vlib/v/tests/array_of_interface_init_test.v | 36 +++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 vlib/v/tests/array_of_interface_init_test.v diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 0f643b5638..6647998a19 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -134,6 +134,11 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type { continue } if expr !is ast.TypeNode { + if c.table.type_kind(elem_type) == .interface_ { + if c.type_implements(typ, elem_type, expr.pos()) { + continue + } + } c.check_expected(typ, elem_type) or { c.error('invalid array element: $err.msg()', expr.pos()) } diff --git a/vlib/v/tests/array_of_interface_init_test.v b/vlib/v/tests/array_of_interface_init_test.v new file mode 100644 index 0000000000..9b4aad6476 --- /dev/null +++ b/vlib/v/tests/array_of_interface_init_test.v @@ -0,0 +1,36 @@ +struct Dog { + breed string +} + +struct Cat { + breed string +} + +fn (d Dog) speak() string { + return 'woof' +} + +fn (c Cat) speak() string { + return 'meow' +} + +interface Speaker { + breed string + speak() string +} + +fn test_array_of_interface_init() { + dog := Dog{'Leonberger'} + cat := Cat{'Siamese'} + + mut rets := []string{} + + for item in [Speaker(dog), cat] { + println(item.speak()) + rets << item.speak() + } + + assert rets.len == 2 + assert rets[0] == 'woof' + assert rets[1] == 'meow' +}