#Difficulty understanding behaviour of std.log.info i.c.w. std.fmt.bufPrint

1 messages · Page 1 of 1 (latest)

spark vault
#

I encountered some behaviour which I don't understand and hope someone can explain it to me. Please check the following code snippet:

const std = @import("std");

pub fn main() !void {
    std.log.info(try format(), .{}); // --> CASE 1
    std.log.info("{s}", .{try format()}); // --> CASE 2
}

fn format() ![]const u8 {
    var result: [10]u8 = undefined;
    return try std.fmt.bufPrint(&result, "{d:0>4}-{d:0>2}-{d:0>2}", .{
        2025,
        1,
        12,
    });
}

The first line (CASE 1) prints the expected string "2025-01-12", but the second line (CASE 2) prints "12". I fail to understand why that is and would like to understand it (as I have a use case where I want to use the returned value as argument).

calm hollow
#

youre returning a pointer to a local variable which means its invalid once the function returns so anything it prints is unreliable. the first one works because the first argument is evaluated at compile time where pointers lifetimes are extended

#

im guessing youre on 0.13 or something because that actually doesnt work anymore. pointers to mutable variables arent allowed to escape their containing scope at comptime

boreal quartz
#

meaning case 1 is now a compile error but case 2 would still produce unpredictable results at runtime

spark vault
#

Ah... That makes sense. Yes, I'm on 0.13 and am just getting started tbh. But I understand the issue now.

#

Yes clear! So I should return a copy of the result array instead of the slice returned by the bufPrint method?

calm hollow
#

thats one way yes and it should work fine here since youre doing padding but more often youll probably want to take in a slice parameter and write to that

spark vault
#

Check, yeah that probably makes more sense. I'll have a go at it. Thanks!!