1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: check generic struct no_keys init (fix #17061) (#17067)

This commit is contained in:
yuyi 2023-01-23 01:11:12 +08:00 committed by GitHub
parent 3aeb6179b7
commit 865c0ea8bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 0 deletions

View File

@ -387,6 +387,15 @@ fn (mut c Checker) struct_init(mut node ast.StructInit) ast.Type {
field.typ = c.expr(field.expr)
field.expected_type = field.typ
}
sym := c.table.sym(c.unwrap_generic(node.typ))
if sym.kind == .struct_ {
info := sym.info as ast.Struct
if node.no_keys && node.fields.len != info.fields.len {
fname := if info.fields.len != 1 { 'fields' } else { 'field' }
c.error('initializing struct `${sym.name}` needs `${info.fields.len}` ${fname}, but got `${node.fields.len}`',
node.pos)
}
}
}
// string & array are also structs but .kind of string/array
.struct_, .string, .array, .alias {

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/generics_struct_nokeys_init_err.vv:6:9: error: initializing struct `Am` needs `1` field, but got `2`
4 |
5 | fn convert[T](num int) T {
6 | return T{num, 1}
| ~~~~~~~~~
7 | }
8 |

View File

@ -0,0 +1,12 @@
struct Am {
inner int
}
fn convert[T](num int) T {
return T{num, 1}
}
fn main() {
println(convert[Am](3).inner)
assert convert[Am](3).inner == 3
}