diff --git a/vlib/v/checker/assign.v b/vlib/v/checker/assign.v index 66bc24f65f..fa410fe7e0 100644 --- a/vlib/v/checker/assign.v +++ b/vlib/v/checker/assign.v @@ -698,6 +698,9 @@ fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) { } } } + if left_sym.kind == .struct_ && right is ast.StructInit && (right as ast.StructInit).is_anon { + c.error('cannot assign anonymous `struct` to a typed `struct`', right.pos()) + } } // this needs to run after the assign stmt left exprs have been run through checker // so that ident.obj is set diff --git a/vlib/v/checker/tests/anon_struct_assign_err.out b/vlib/v/checker/tests/anon_struct_assign_err.out new file mode 100644 index 0000000000..bc6691e500 --- /dev/null +++ b/vlib/v/checker/tests/anon_struct_assign_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/anon_struct_assign_err.vv:9:12: error: cannot assign anonymous `struct` to a typed `struct` + 7 | } + 8 | println(y) + 9 | y = struct { + | ^ + 10 | name: 'Def' + 11 | } diff --git a/vlib/v/checker/tests/anon_struct_assign_err.vv b/vlib/v/checker/tests/anon_struct_assign_err.vv new file mode 100644 index 0000000000..ff6edc194a --- /dev/null +++ b/vlib/v/checker/tests/anon_struct_assign_err.vv @@ -0,0 +1,12 @@ +struct Abc { + name string +} + +mut y := Abc{ + name: 'Abc' +} +println(y) +y = struct { + name: 'Def' +} +println(y)