Hi all, absolute zig noobie here, I would like to parse an integer from command line args on Linux , I know how to iterate over them and print them as strings thanks to a tutorial from dude the builder but I can’t figure out how to convert a string to an int
src/main.zig:18:44: error: expected type '[]const u8', found '?[:0]const u8'
The call to args_no_alloc_iter.next() returns an optional (note the ? in the found '?[:0]const u8' part), which you need to unwrap before use (it may be null). For your quick example, you might want to do something like this:
var args_no_alloc_iter = process.args();
_ args_no_alloc_iter.next();
const second_arg = args_no_alloc_iter.next() orelse {
std.log.err("Second arg is missing!", .{});
return;
};
const num = try std.fmt.parseInt(i32, second_arg, 10);
The orelse will check if the optional is null - if it is, it will do what’s in the block (which ends with a return, so it’ll jump out of the current function); if it isn’t null, the block is skipped and you carry onto the const num = ... assignment.
++ can only be used to concatenate comptime strings, and name: []u8 is a runtime string.
You can allocate a runtime string on the heap that is the size you need, then copy the two strings into it using slices and @memcpy. You’ll need an Allocator and the caller will own the returned string, so the caller will eventually need to free the string using the Allocator.
You can pass a buffer (declared on the stack, for example) down to the hello method as a parameter, and then use @memcpy to copy the two strings into the buffer. Then you can return a slice of the buffer. The caller owns the memory because it owns the buffer. This can sometimes be used to avoid heap allocation.
EDIT: I suggest reading the Memory section of the docs: