std.fmt in Zig
Format into a stack buffer and parse back out — no allocator in sight.
const std = @import("std");
pub fn main() !void {
// bufPrint formats into a stack buffer -- no allocator involved.
var buf: [48]u8 = undefined;
const line = try std.fmt.bufPrint(&buf, "day {d} mean {d:.2}", .{
3, 68.14,
});
std.debug.print("built: [{s}]\n", .{line});
// parseInt and parseFloat go the other way.
const day = try std.fmt.parseInt(u8, line[4..5], 10);
const mean = try std.fmt.parseFloat(f32, "68.14");
std.debug.print("parsed back: day {d}, mean {d:.2}\n", .{ day, mean });
}
How it works
bufPrintwrites intobufand returns the slice it used.{d:.2}fixes the decimals the same way in every print.parseIntandparseFloatreturn error unions, unwrapped here withtry.
Keywords and builtins used here
constf32fnpubtryu8varvoid
The run, in numbers
- Lines
- 15
- Characters to type
- 494
- Tokens
- 133
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 123 seconds.
Step 2 of 3 in The standard library, step 23 of 27 in Language basics.