如何在编译时在 Zig 中连接两个字符串文字?

问题描述

如何在 Zig 中连接以下长度在编译时已知的字符串?

const url = "https://github.com/{}/reponame";
const user = "Himujjal";
const final_url = url + user; // ??

解决方法

数组连接运算符,用于两个 comptime 已知字符串:

const final_url = "https://github.com/" ++ user ++ "/reponame";

std.fmt.comptimePrint 用于 comptime 已知的字符串和数字以及其他可格式化的内容:

const final_url = comptime std.fmt.comptimePrint("https://github.com/{}/reponame",.{user});

运行时,带分配:

const final_url = try std.fmt.allocPrint(alloc,"https://github.com/{}/reponame",.{user});
defer alloc.free(final_url);

运行时,无分配,具有已知的最大长度:

var buffer = [_]u8{undefined} ** 100;
const printed = try std.fmt.bufPrint(&buffer,.{user});
,

这很容易做到。缺乏研究产生了这个问题。但对于任何想知道的人。

const final_url = "https://github.com/" ++ user ++ "/reponame";

欲了解更多信息,请访问:comptime in zig