From 89bb85cd037b424ae93f59ffbefbde75b4fe51b4 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 20 Jan 2025 10:53:16 +0800 Subject: [PATCH] cgen: fix interface casting in anon fn --- vlib/v/gen/c/cgen.v | 1 + .../interface_as_cast_in_anon_fn_test.v | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 vlib/v/tests/interfaces/interface_as_cast_in_anon_fn_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 36830e82cac738..b7305b28ca680c 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1157,6 +1157,7 @@ pub fn (mut g Gen) write_typeof_functions() { g.writeln('\tif (sidx == _${sym.cname}_${sub_sym.cname}_index) return "${util.strip_main_name(sub_sym.name)}";') } g.writeln2('\treturn "unknown ${util.strip_main_name(sym.name)}";', '}') + g.definitions.writeln('int v_typeof_interface_idx_${sym.cname}(int sidx);') g.writeln2('', 'int v_typeof_interface_idx_${sym.cname}(int sidx) {') if g.pref.parallel_cc { g.extern_out.writeln('extern int v_typeof_interface_idx_${sym.cname}(int sidx);') diff --git a/vlib/v/tests/interfaces/interface_as_cast_in_anon_fn_test.v b/vlib/v/tests/interfaces/interface_as_cast_in_anon_fn_test.v new file mode 100644 index 00000000000000..e7b00c4db40bb6 --- /dev/null +++ b/vlib/v/tests/interfaces/interface_as_cast_in_anon_fn_test.v @@ -0,0 +1,26 @@ +@[heap] +struct Foo { +mut: + val int +} + +@[heap] +struct Bar { +mut: + val int +} + +interface FooBar { +mut: + val int +} + +fn test_interface_as_cast_in_anon_fn() { + mut fbs := []&FooBar{} + fbs << &Foo{1} + do_something := fn [mut fbs] () { + _ := fbs.last() as Foo // this line works outside of anon fn + } + do_something() + assert true +}