From 598d18cbd97fab7153bfaa9b99ed14d486bc889a Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 19 Dec 2020 13:55:13 +0800 Subject: [PATCH] cgen: fix default zero in map fields (fix #7328) (#7394) --- vlib/builtin/map_test.v | 13 +++++++++++++ vlib/v/gen/cgen.v | 19 ++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/vlib/builtin/map_test.v b/vlib/builtin/map_test.v index 49e9c59974..83c5a2b934 100644 --- a/vlib/builtin/map_test.v +++ b/vlib/builtin/map_test.v @@ -440,3 +440,16 @@ fn test_map_clone() { assert nums2['foo'] == 2 assert nums2['bar'] == 8 } + +struct MValue { + name string + misc map[string]string +} + +fn test_map_default_zero() { + m := map[string]MValue{} + v := m['unknown'] + x := v.misc['x'] + println(x) + assert x == '' +} diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 222af09c97..cf2d3ac343 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -5414,7 +5414,24 @@ fn (mut g Gen) type_default(typ_ table.Type) string { // User struct defined in another module. // if typ.contains('__') { if sym.kind == .struct_ { - return '{0}' + mut has_array_map := false + mut zero_str := '{' + info := sym.info as table.Struct + for field in info.fields { + field_sym := g.table.get_type_symbol(field.typ) + if field_sym.kind in [.array, .map] { + zero_str += '.$field.name=${g.type_default(field.typ)},' + has_array_map = true + } + } + if has_array_map { + zero_str += '}' + type_name := g.typ(typ) + zero_str = '($type_name)' + zero_str + } else { + zero_str += '0}' + } + return zero_str } // if typ.ends_with('Fn') { // TODO // return '0'