Skip to content

Instantly share code, notes, and snippets.

@doccaico
Created April 10, 2024 12:17
Show Gist options
  • Save doccaico/80a62796fe2f48045c6871309bd5f737 to your computer and use it in GitHub Desktop.
Save doccaico/80a62796fe2f48045c6871309bd5f737 to your computer and use it in GitHub Desktop.
Zig version of Golang's string(ch)
const std = @import("std");
const fmt = std.fmt;
const mem = std.mem;
const print = std.debug.print;
const assert = std.debug.assert;
const expect = std.testing.expect;
pub var allocator: std.mem.Allocator = undefined;
const S = struct {
str: []const u8,
};
fn echo(str: []const u8) void {
print(" echo: {s}\n", .{str});
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
allocator = arena.allocator();
const ch: u8 = 'a';
{
const slice = try allocator.alloc(u8, 1);
slice[0] = ch;
const s = S{ .str = slice };
print("new_slice: {s}\n", .{slice});
print("S.str: {s}\n", .{s.str});
echo(slice);
}
{
const new_slice = blk: {
const slice = try allocator.alloc(u8, 1);
slice[0] = ch;
break :blk slice;
};
const s = S{ .str = new_slice };
print("new_slice: {s}\n", .{new_slice});
print("S.str: {s}\n", .{s.str});
echo(new_slice);
}
// feels a bit ugly
{
const s = S{ .str = blk: {
const slice = try allocator.alloc(u8, 1);
slice[0] = ch;
break :blk slice;
} };
print("S.str: {s}\n", .{s.str});
echo(s.str);
}
}
// new_slice: a
// S.str: a
// echo: a
// new_slice: a
// S.str: a
// echo: a
// S.str: a
// echo: a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment