From 5d7958db7d979de19102a22e2acaf52efb7eb599 Mon Sep 17 00:00:00 2001 From: Larsimusrex Date: Sat, 13 Sep 2025 06:57:01 +0200 Subject: [PATCH] cgen: fix generic cast to sumtype of empty struct (fix #25263) (#25290) --- vlib/v/gen/c/cgen.v | 3 ++- .../tests/sumtypes/sumtype_empty_struct_test.v | 18 ++++++++++++++++++ vlib/x/json2/types.v | 4 +--- 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 vlib/v/tests/sumtypes/sumtype_empty_struct_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index d7675eb2b..db2fa815b 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -7574,8 +7574,9 @@ fn (mut g Gen) type_default_impl(typ_ ast.Type, decode_sumtype bool) string { } } .struct { - mut has_none_zero := false info := sym.info as ast.Struct + mut has_none_zero := info.fields.len == 0 + mut init_str := if info.is_anon && !g.inside_global_decl { '(${g.styp(typ)}){' } else { diff --git a/vlib/v/tests/sumtypes/sumtype_empty_struct_test.v b/vlib/v/tests/sumtypes/sumtype_empty_struct_test.v new file mode 100644 index 000000000..40bd3402a --- /dev/null +++ b/vlib/v/tests/sumtypes/sumtype_empty_struct_test.v @@ -0,0 +1,18 @@ +struct Empty { +} + +type Sum = int | Empty + +fn do_generic[T](val T) T { + $for v in Sum.variants { + if val is v { + return T(v) + } + } + return T{} +} + +fn test_empty_cast() { + assert do_generic(Sum(0)) == Sum(0) + assert do_generic(Sum(Empty{})) == Sum(Empty{}) +} diff --git a/vlib/x/json2/types.v b/vlib/x/json2/types.v index b9a71fd5b..e60068670 100644 --- a/vlib/x/json2/types.v +++ b/vlib/x/json2/types.v @@ -24,9 +24,7 @@ pub type Any = []Any | Null // Null is a simple representation of the `null` value in JSON. -pub struct Null { - is_null bool = true -} +pub struct Null {} // null is an instance of the Null type, to ease comparisons with it. pub const null = Null{} -- 2.39.5