diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index f47e63d75d77b0..715057e0e83938 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -616,6 +616,8 @@ fn (mut g Gen) struct_init_field(sfield ast.StructInitField, language ast.Langua if (sfield.expected_type.has_flag(.option) && !sfield.typ.has_flag(.option)) || (sfield.expected_type.has_flag(.result) && !sfield.typ.has_flag(.result)) { g.expr_with_opt(sfield.expr, sfield.typ, sfield.expected_type) + } else if sfield.expr is ast.LambdaExpr && sfield.expected_type.has_flag(.option) { + g.expr_opt_with_cast(sfield.expr, sfield.typ, sfield.expected_type) } else { g.left_is_opt = true g.expr_with_cast(sfield.expr, sfield.typ, sfield.expected_type) diff --git a/vlib/v/tests/anon_fn_option_test.v b/vlib/v/tests/anon_fn_option_test.v new file mode 100644 index 00000000000000..dd25f412daefd2 --- /dev/null +++ b/vlib/v/tests/anon_fn_option_test.v @@ -0,0 +1,26 @@ +struct Foo { + bar ?fn () +} + +fn test_main() { + foo1 := Foo{ + bar: || println('foo1') + } + foo2 := Foo{ + bar: fn () { + println('foo2') + } + } + if bar_fn := foo1.bar { + bar_fn() + assert true + } else { + assert false + } + if bar_fn := foo2.bar { + bar_fn() + assert true + } else { + assert false + } +}