#How would I make a toString function for my Vector4 struct?

1 messages · Page 1 of 1 (latest)

low shard
#

I tried this:

    pub fn toString(self: Vector4) []const u8 {
        var buffer: [2048]u8 = undefined;

        const str = try std.fmt.bufPrint(&buffer, "{}, {}, {}, {}", .{ self.x, self.y, self.z, self.w });

        return str;
    }

But apparently I'm returning a pointer that no longer exists after returning, so it always gives me an error. What are my alternatives?

jaunty wolf
#

Accept a writer or allocator into your function

low shard
#

Should I use allocPrint then?

stuck geode
#

If you accept an allocator, then you'd use std.fmt.allocPrint. If you accept a buffer, than you'd use what you're using, if you accept a writer, then you'd use std.fmt.format.

low shard
#

I'm using allocPrint now

#

My test don't pass tho

#
pub fn toString(self: Vector4, allocator: std.mem.Allocator) ![]const u8 {
        return std.fmt.allocPrint(allocator, "{}, {}, {}, {}", .{ self.x, self.y, self.z, self.w });
    }
#

yikes, hang on

#

Doesn't give me the error anymore

#

But test don't pass

stuck geode
#

FYI: Zig has these magic methods that are poorly documented.

One is "format". If you do:

  pub fn format(self: Vector4, comptime _: []const u8, _: std.fmt.FormatOptions, out: anytype) !void {
    return std.fmt.format(out, "{} {} {} {}", .{self.x, self.y, self.z, self.w});
  }

Then you'd be able to use the vector4 as an format argument directly.

(which would mean that the user of your library would then have the flexibility to stringify a vector using a writer, or a buffer, or an allocator)

#

Hard to tell why they don't pass, maybe use the verbosely named testing.expectEqualStrings to get an more useful printout of actual vs expected.

low shard
#

ty!

#

Oh, ok it's because it's returning this?

#

Oh, it is always returning with scietific notation

#

But not even in a way that works lol

final cipher
#

Use {d}

#

For decimal printing of floats

low shard
#

oh thank you

#

When I read about printing decimals, my mind went to c#

#

And completely forgot Zig doesn't have the decimal type like in c#