diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index c1574973f0..9e73ed69fa 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -5459,24 +5459,32 @@ fn (mut g Gen) type_default(typ_ table.Type) string { // User struct defined in another module. // if typ.contains('__') { if sym.kind == .struct_ { - mut has_array_map := false - mut zero_str := '{' + mut has_none_zero := false + mut init_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 field_sym.kind in [.array, .map] || field.has_default_expr { + if field.has_default_expr { + pos := g.out.len + g.expr(ast.fe2ex(field.default_expr)) + expr_str := g.out.after(pos) + g.out.go_back(expr_str.len) + init_str += '.$field.name = $expr_str,' + } else { + init_str += '.$field.name = ${g.type_default(field.typ)},' + } + has_none_zero = true } } - if has_array_map { - zero_str += '}' + if has_none_zero { + init_str += '}' type_name := g.typ(typ) - zero_str = '($type_name)' + zero_str + init_str = '($type_name)' + init_str } else { - zero_str += '0}' + init_str += '0}' } - return zero_str + return init_str } // if typ.ends_with('Fn') { // TODO // return '0' diff --git a/vlib/v/tests/struct_child_field_default_test.v b/vlib/v/tests/struct_child_field_default_test.v new file mode 100644 index 0000000000..2932282734 --- /dev/null +++ b/vlib/v/tests/struct_child_field_default_test.v @@ -0,0 +1,22 @@ +struct Position { + line_nr int = 1 +} + +struct Statement { + pos Position +} + +struct Expression { + pos Position +} + +fn test_child_struct_field_default() { + stmt := Statement{ + pos: Position{} + } + expr := Expression{} + println(stmt) + println(expr) + assert stmt.pos.line_nr == 1 + assert expr.pos.line_nr == 1 +}