From 9ae8cc357f55ffe21bc856847d9fdb8f202ac5bb Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 8 Mar 2025 15:58:03 -0300 Subject: [PATCH] checker: fix option ptr field assign checking (fix #23879) (#23880) --- vlib/v/checker/struct.v | 3 +- vlib/v/tests/options/option_ptr_field_test.v | 40 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/options/option_ptr_field_test.v diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index 645103c566..0593a593ca 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -713,8 +713,7 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini if got_type.has_flag(.result) { c.check_expr_option_or_result_call(init_field.expr, init_field.typ) } - if exp_type_is_option && got_type.is_ptr() && !(exp_type.is_ptr() - && exp_type_sym.kind == .struct) { + if exp_type_is_option && got_type.is_ptr() && !exp_type.is_ptr() { c.error('cannot assign a pointer to option struct field', init_field.pos) } if exp_type_sym.kind == .voidptr && got_type_sym.kind == .struct diff --git a/vlib/v/tests/options/option_ptr_field_test.v b/vlib/v/tests/options/option_ptr_field_test.v new file mode 100644 index 0000000000..4716d45a55 --- /dev/null +++ b/vlib/v/tests/options/option_ptr_field_test.v @@ -0,0 +1,40 @@ +module main + +@[heap] +interface IGameObject { +mut: + name string + parent ?&IGameObject +} + +@[heap] +struct GameObject implements IGameObject { +mut: + name string + parent ?&IGameObject +} + +struct Ship implements IGameObject { + GameObject + speed f32 +} + +fn test_main() { + mut world := &GameObject{ + name: 'world' + } + mut ship := &Ship{ + name: 'ship' + parent: world + } + assert '${ship}' == "&Ship{ + GameObject: GameObject{ + name: 'ship' + parent: &Option(IGameObject(GameObject{ + name: 'world' + parent: &Option(none) + })) + } + speed: 0.0 +}" +}