From 570a12da8df8481184e0c631f2d5a851c51c4a13 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 26 Aug 2023 03:50:53 +0800 Subject: [PATCH] cgen: fix generic struct with option fn field (#19218) --- vlib/v/gen/c/cgen.v | 2 +- vlib/v/tests/generics_struct_with_option_fn_test.v | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/generics_struct_with_option_fn_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index b558e8f0b23f8b..59ceb54dbea487 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -3603,7 +3603,7 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) { if node.or_block.kind != .absent && !g.is_assign_lhs && g.table.sym(node.typ).kind != .chan { is_ptr := sym.kind in [.interface_, .sum_type] stmt_str := g.go_before_stmt(0).trim_space() - styp := g.typ(node.typ) + styp := g.typ(g.unwrap_generic(node.typ)) g.empty_line = true tmp_var := g.new_tmp_var() g.write('${styp} ${tmp_var} = ') diff --git a/vlib/v/tests/generics_struct_with_option_fn_test.v b/vlib/v/tests/generics_struct_with_option_fn_test.v new file mode 100644 index 00000000000000..b3ba7d053b28a9 --- /dev/null +++ b/vlib/v/tests/generics_struct_with_option_fn_test.v @@ -0,0 +1,14 @@ +struct Cmp[K] { + cmp ?fn (K, K) bool +} + +fn (c Cmp[K]) compare(a K, b K) bool { + cmp := c.cmp or { return a < b } + return cmp(a, b) +} + +fn test_generic_struct_with_option_fn() { + c := Cmp[int]{} + print(c.compare(1, 2)) + assert c.compare(1, 2) +}