How to concat two string literals at compile time in Zig?
Asked Answered
G

2

8

How to do concat the following strings whose length are known at compile time in Zig?

const url = "https://github.com/{}/reponame";
const user = "Himujjal";
const final_url = url + user; // ??
Goetz answered 8/3, 2021 at 9:35 Comment(0)
R
21

Array concatenation operator, for two comptime-known strings:

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

std.fmt.comptimePrint for comptime-known strings and numbers and other formattable things:

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

Runtime, with allocation:

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

Runtime, no allocation, with a comptime-known maximum length:

var buffer = [_]u8{undefined} ** 100;
const printed = try std.fmt.bufPrint(&buffer, "https://github.com/{s}/reponame", .{user});

Runtime, using ArrayList

var string = std.ArrayList(u8).init(gpa);
defer string.deinit();
try string.appendSlice("https://github.com/");
try string.appendSlice(user);
try string.appendSlice("/reponame");
const final_url = string.items;
Roxieroxine answered 17/3, 2021 at 1:14 Comment(0)
G
0

Its an easy thing to do. Lack of research produced this question. But for anyone wondering.

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

For more information go through: comptime in zig.

Goetz answered 8/3, 2021 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.