diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index 16186da5b58f8a..91cca4e3f1c477 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -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_ diff --git a/vlib/v/checker/tests/struct_field_init_with_result_err.out b/vlib/v/checker/tests/struct_field_init_with_result_err.out new file mode 100644 index 00000000000000..f21302d6e7ff3d --- /dev/null +++ b/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 | } diff --git a/vlib/v/checker/tests/struct_field_init_with_result_err.vv b/vlib/v/checker/tests/struct_field_init_with_result_err.vv new file mode 100644 index 00000000000000..20617ce2d9a569 --- /dev/null +++ b/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()}) +}