Hello! I am trying to write a function that would take a user input and return it as a string.
I have made this function so far:
fn ask_user(comptime instruction: []const u8) ![]const u8 {
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
if (!std.mem.eql(u8, instruction, "")) {
try stdout.print(instruction, .{});
}
const bare_line = try stdin.readUntilDelimiterAlloc(
std.heap.page_allocator,
'\n',
10,
);
defer std.heap.page_allocator.free(bare_line);
const line = std.mem.trim(u8, bare_line, "\r");
print("in ask user: |{s}|\n", .{line});
return line;
}
pub fn main() !void {
var user_input = try ask_user("your turn: ");
print("user input: |{s}|\n", .{user_input});
}
The print statement in ask_user displays the expected string. There is no compilation error. However, during execution, the main function panics: panic: reached unreachable code. I am assuming it's because the line variable is "de-allocated" after the function returns. However, after reading this article (https://zig.news/kristoff/what-s-a-string-literal-in-zig-31e9), I was expecting the code to be working.
I don't know what I am missing, could someone help me?