#Debug print to not print scientific notation for struct

1 messages · Page 1 of 1 (latest)

mystic spade
#

say I have something like this code:

const std = @import("std");

pub const struck = struct {
    a: f32 = 240,
    b: f32 = 30000,
    c: f32 = 666,
};

pub fn main() !void {
    const s: struck = struck{};
    std.debug.print("{}\n", .{s});
}

it will output this

main.struck{ .a = 2.4e2, .b = 3e4, .c = 6.66e2 }

but what I really wanted was this

main.struck{ .a = 240 .b = 30000 .c = 666 }

Other than putting {d} for every struct value, is there an easier way for me to format this as non-scientific numbers?

void crown
#

create a format method in your struck

#

read doc comment of std.fmt.format

mystic spade
#

okay so I see this comment

#

If a formatted user type contains a function of the type

pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void

with ? being the type formatted, this function will be called instead of the default implementation. This allows user types to be formatted in a logical manner instead of dumping all fields of the type.

A user type may be a struct, vector, union or enum type.

To print literal curly braces, escape them by writing them twice, e.g. {{ or }}.

#

However, I'm not sure I understand fully how to utilize the value parameter in that function

#

here's what I have so far

#
pub const struck = struct {
    a: f32 = 240,
    b: f32 = 30000,
    c: f32 = 666,
    pub fn format(value: struck, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
        _ = value;
        try writer.print(fmt, options);
    }
};
vale falcon
#

for example, you might want something like```ts
try writer.print(".{{ .a = {d}, .b = {d}, .c = {d} }}", .{ value.a, value.b, value.c })

mystic spade