checker: fix error for array of interface init in for_in (#13636)

pull/13643/head
yuyi 2022-03-03 18:32:55 +08:00 committed by GitHub
parent 3364f2aadf
commit ac1b31dbba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -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())
}

View File

@ -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'
}