Skip to content

Commit

Permalink
cgen: fix lambda initialization on option struct field (fix #19474) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Nov 27, 2023
1 parent fc99781 commit 8ba04d3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions vlib/v/gen/c/struct.v
Expand Up @@ -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)
Expand Down
26 changes: 26 additions & 0 deletions 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
}
}

0 comments on commit 8ba04d3

Please sign in to comment.