diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 8c601c54cf..93d488e308 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -468,19 +468,7 @@ pub fn (mut f Fmt) struct_decl(node ast.StructDecl) { } if field.has_default_expr { f.write(' = ') - mut is_pe_amp_ce := false - mut ce := ast.CastExpr{} - if field.default_expr is ast.PrefixExpr { - pe := field.default_expr as ast.PrefixExpr - if pe.right is ast.CastExpr && pe.op == .amp { - ce = pe.right as ast.CastExpr - is_pe_amp_ce = true - f.expr(ce) - } - } - if !is_pe_amp_ce { - f.expr(field.default_expr) - } + f.struct_field_expr( field.default_expr ) } // f.write('// $field.pos.line_nr') if field.comment.text != '' && field.comment.pos.line_nr == field.pos.line_nr { @@ -497,6 +485,23 @@ pub fn (mut f Fmt) struct_decl(node ast.StructDecl) { f.writeln('}\n') } + +pub fn (mut f Fmt) struct_field_expr(fexpr ast.Expr) { + mut is_pe_amp_ce := false + mut ce := ast.CastExpr{} + if fexpr is ast.PrefixExpr { + pe := fexpr as ast.PrefixExpr + if pe.right is ast.CastExpr && pe.op == .amp { + ce = pe.right as ast.CastExpr + is_pe_amp_ce = true + f.expr(ce) + } + } + if !is_pe_amp_ce { + f.expr(fexpr) + } +} + fn (f &Fmt) type_to_str(t table.Type) string { mut res := f.table.type_to_str(t) if res.ends_with('_ptr') { @@ -626,7 +631,7 @@ pub fn (mut f Fmt) expr(node ast.Expr) { ktyp = minfo.key_type vtyp = minfo.value_type } - + f.write('map[') f.write(f.type_to_str(ktyp)) f.write(']') @@ -1152,7 +1157,7 @@ pub fn (mut f Fmt) struct_init(it ast.StructInit) { f.write('$name{') // } for i, field in it.fields { - f.expr(field.expr) + f.struct_field_expr(field.expr) if i < it.fields.len - 1 { f.write(', ') } @@ -1167,7 +1172,7 @@ pub fn (mut f Fmt) struct_init(it ast.StructInit) { f.indent++ for field in it.fields { f.write('$field.name: ') - f.expr(field.expr) + f.struct_field_expr(field.expr) f.writeln('') } f.indent-- diff --git a/vlib/v/fmt/tests/struct_init_with_custom_len_keep.vv b/vlib/v/fmt/tests/struct_init_with_custom_len_keep.vv new file mode 100644 index 0000000000..1daa3cb5db --- /dev/null +++ b/vlib/v/fmt/tests/struct_init_with_custom_len_keep.vv @@ -0,0 +1,17 @@ +struct Foo { + i int + a []int +} + +struct Bar { + f &Foo = &Foo(0) + d Foo = Foo(0) +} + +fn main() { + size := 5 + f := &Foo{ + a: []int{len: int(size)} + } + println('f.a: $f.a') +} diff --git a/vlib/v/fmt/tests/struct_init_with_ref_cast_keep.vv b/vlib/v/fmt/tests/struct_init_with_ref_cast_keep.vv new file mode 100644 index 0000000000..006e4f7354 --- /dev/null +++ b/vlib/v/fmt/tests/struct_init_with_ref_cast_keep.vv @@ -0,0 +1,22 @@ +struct Foo { + f int = 123 +} + +struct Bar { + f &Foo = &Foo(0) +} + +struct Zar { + f Foo +} + +fn main() { + b := &Bar{ + f: &Foo(32) + } + c := &Zar{ + f: Foo{456} + } + assert ptr_str(b.f) == '20' + assert c.f.f == 456 +}