test "init TextChunk" {
var da = std.heap.DebugAllocator(.{}){};
defer _ = da.deinit();
const alc = da.allocator();
var tc1 = try TextChunk.init(alc, .{"aaa"});
defer tc1.deinit(alc);
try expect(mem.eql(u8, tc1.chars.items, "\x1b[22;23;24;27;39;49maaa"));
}
This works but I can’t manage to coerce that string literal "aaa" to a []const u8, I need that switch over @typeInfo(T) to find out it’s a string.
If I call it like this
var tc1 = try TextChunk.init(alc, .{@as([]const u8, "aaa")});
then it works also without the @typeInfo switch, but I’d like to avoid that cast at every call site. I have the impression I’m doing something wrong, is there another way to coerce that string literal into []const u8?
You can use @compileLog to see what type you get from string literals when accepting anytype, that should explain why expecting a slice wasn’t working. Also be aware that sometimes somebody can also give you a [] u8 (which won’t match []const u8, which will also not match [:0]u8 nor [:0]const u8).
You might want have a dedicated function that only deals with strings so that you can simplify some generic code.
Checking if an argument of some unknown type is string-like and coercible to []const u8 requires a bit of reflection effort, since it could be a single-item pointer to an array instead of an actual slice, and/or be mutable and/or have a 0 sentinel.
I don’t think this is applicable to your case, but if you just want a compiler error if it’s not coercible, you can just assign it to a variable with an explicit type.