diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index c5ae14777be139..8ff9283f912cac 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -432,16 +432,21 @@ fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type { node.key_type = info.key_type node.value_type = info.value_type return node.typ - } else { - if sym.kind == .struct { - c.error('`{}` can not be used for initialising empty structs any more. Use `${c.table.type_to_str(c.expected_type)}{}` instead.', - node.pos) + } else if sym.info is ast.Struct { + msg := if sym.info.is_anon { + '`{}` cannot be used to initialize anonymous structs. Use `struct{}` instead.' } else { - c.error('invalid empty map initialisation syntax, use e.g. map[string]int{} instead', - node.pos) + '`{}` can not be used for initialising empty structs any more. Use `${c.table.type_to_str(c.expected_type)}{}` instead.' } - return ast.void_type + c.error(msg, node.pos) + if sym.info.is_anon { + return c.expected_type + } + } else { + c.error('invalid empty map initialisation syntax, use e.g. map[string]int{} instead', + node.pos) } + return ast.void_type } // `x := map[string]string` - set in parser if node.typ != 0 { diff --git a/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out new file mode 100644 index 00000000000000..7f5410f08fa09c --- /dev/null +++ b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv:9:22: error: `{}` cannot be used to initialize anonymous structs. Use `struct{}` instead. + 7 | + 8 | fn main() { + 9 | s := AStructName{5, {}} + | ~~ + 10 | println(s) + 11 | } diff --git a/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv new file mode 100644 index 00000000000000..81f99bd9bfe492 --- /dev/null +++ b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv @@ -0,0 +1,11 @@ +struct AStructName { + foo int + anon struct { + bar int + } +} + +fn main() { + s := AStructName{5, {}} + println(s) +}