Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: clarify error message about using empty map literal to initialize structs #22534

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions vlib/v/checker/containers.v
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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 | }
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
struct AStructName {
foo int
anon struct {
bar int
}
}

fn main() {
s := AStructName{5, {}}
println(s)
}
Loading