From 690c0309ad26fdae159115530726df9c217be3e7 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 8 Apr 2021 13:24:34 +0800 Subject: [PATCH] vfmt: fix fn/method that return generic struct (#9638) --- vlib/v/ast/types.v | 15 +++++++ .../tests/fn_return_generic_struct_keep.vv | 39 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 vlib/v/fmt/tests/fn_return_generic_struct_keep.vv diff --git a/vlib/v/ast/types.v b/vlib/v/ast/types.v index c1617cd4c6..503076188b 100644 --- a/vlib/v/ast/types.v +++ b/vlib/v/ast/types.v @@ -930,6 +930,21 @@ pub fn (t &Table) type_to_str_using_aliases(typ Type, import_aliases map[string] } res += ')' } + .struct_ { + if typ.has_flag(.generic) { + info := sym.info as Struct + res += '<' + for i, gtyp in info.generic_types { + res += t.get_type_symbol(gtyp).name + if i != info.generic_types.len - 1 { + res += ', ' + } + } + res += '>' + } else { + res = t.shorten_user_defined_typenames(res, import_aliases) + } + } .void { if typ.has_flag(.optional) { return '?' diff --git a/vlib/v/fmt/tests/fn_return_generic_struct_keep.vv b/vlib/v/fmt/tests/fn_return_generic_struct_keep.vv new file mode 100644 index 0000000000..b85781e118 --- /dev/null +++ b/vlib/v/fmt/tests/fn_return_generic_struct_keep.vv @@ -0,0 +1,39 @@ +pub struct Optional { +mut: + value T + some bool +} + +pub struct Foo { + foo int +} + +pub fn (f Foo) new_some(value T) Optional { + return { + value: value + some: true + } +} + +pub fn (f Foo) some(opt Optional) bool { + return opt.some +} + +pub fn (f Foo) get(opt Optional) T { + return opt.value +} + +pub fn (f Foo) set(mut opt Optional, value T) { + opt.value = value + opt.some = true +} + +fn main() { + foo := Foo{} + mut o := foo.new_some(23) + println(foo.some(o)) + assert foo.some(o) == true + foo.set(mut o, 42) + println(foo.get(o)) + assert foo.get(o) == 42 +}