From 29f372ff5b94f0542684fe3941a4cd8a36f307c7 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Fri, 13 Dec 2024 03:03:35 -0300 Subject: [PATCH] cgen: fix codegen for returning option reference from indexexpr (fix #23133) (#23139) --- vlib/v/gen/c/index.v | 6 ++++- vlib/v/tests/options/option_index_amp_test.v | 28 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/options/option_index_amp_test.v diff --git a/vlib/v/gen/c/index.v b/vlib/v/gen/c/index.v index 9d8bf1830..76f6dedd4 100644 --- a/vlib/v/gen/c/index.v +++ b/vlib/v/gen/c/index.v @@ -325,7 +325,11 @@ fn (mut g Gen) index_of_array(node ast.IndexExpr, sym ast.TypeSymbol) { if !node.is_option { g.or_block(tmp_opt, node.or_expr, elem_type) } - g.write('\n${cur_line}(*(${elem_type_str}*)${tmp_opt}.data)') + if !g.is_amp { + g.write('\n${cur_line}(*(${elem_type_str}*)${tmp_opt}.data)') + } else { + g.write('\n${cur_line}*${tmp_opt_ptr}') + } } } } diff --git a/vlib/v/tests/options/option_index_amp_test.v b/vlib/v/tests/options/option_index_amp_test.v new file mode 100644 index 000000000..73ced1f49 --- /dev/null +++ b/vlib/v/tests/options/option_index_amp_test.v @@ -0,0 +1,28 @@ +module main + +struct Bar { + name string +} + +struct Foo { + bars []Bar +} + +fn (f Foo) find() ?&Bar { + return &f.bars[1] or { return none } +} + +fn test_main() { + foo := Foo{ + bars: [Bar{ + name: '123' + }, Bar{ + name: 'aaa' + }, Bar{ + name: 's34' + }] + } + bar := foo.find() or { panic('not found') } + println(bar.name) + assert bar.name == 'aaa' +} -- 2.39.5