Skip to content

Commit

Permalink
checker: check struct field init with result value (fix #18511) (#18514)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Jun 22, 2023
1 parent 0b2e947 commit 68ba390
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
5 changes: 4 additions & 1 deletion vlib/v/checker/struct.v
Expand Up @@ -509,11 +509,14 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini
if got_type == ast.void_type {
c.error('`${init_field.expr}` (no value) used as value', init_field.pos)
}
if !exp_type.has_flag(.option) && !got_type.has_flag(.result) {
if !exp_type.has_flag(.option) {
got_type = c.check_expr_opt_call(init_field.expr, got_type)
if got_type.has_flag(.option) {
c.error('cannot assign an Option value to a non-option struct field',
init_field.pos)
} else if got_type.has_flag(.result) {
c.error('cannot assign a Result value to a non-option struct field',
init_field.pos)
}
}
if exp_type_sym.kind == .voidptr && got_type_sym.kind == .struct_
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/checker/tests/struct_field_init_with_result_err.out
@@ -0,0 +1,6 @@
vlib/v/checker/tests/struct_field_init_with_result_err.vv:10:18: error: example() returns a Result, so it should have either an `or {}` block, or `!` at the end
8 |
9 | fn main() {
10 | println(Example{example()})
| ~~~~~~~~~
11 | }
11 changes: 11 additions & 0 deletions vlib/v/checker/tests/struct_field_init_with_result_err.vv
@@ -0,0 +1,11 @@
fn example() !int {
return 0
}

struct Example {
example int
}

fn main() {
println(Example{example()})
}

0 comments on commit 68ba390

Please sign in to comment.