1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: check struct field init with result value (fix #18511) (#18514)

This commit is contained in:
yuyi 2023-06-23 03:40:11 +08:00 committed by GitHub
parent 0b2e947e0c
commit 68ba39084d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 1 deletions

View File

@ -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 { if got_type == ast.void_type {
c.error('`${init_field.expr}` (no value) used as value', init_field.pos) 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) got_type = c.check_expr_opt_call(init_field.expr, got_type)
if got_type.has_flag(.option) { if got_type.has_flag(.option) {
c.error('cannot assign an Option value to a non-option struct field', c.error('cannot assign an Option value to a non-option struct field',
init_field.pos) 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_ if exp_type_sym.kind == .voidptr && got_type_sym.kind == .struct_

View File

@ -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 | }

View File

@ -0,0 +1,11 @@
fn example() !int {
return 0
}
struct Example {
example int
}
fn main() {
println(Example{example()})
}