Hi everyone, how are you?
I’m facing a strange problem, and I can’t identify the reason for the error.
The problem is occurring with the use of the parseInt
function, when I use it directly in the main, there are no problems, however, if I use the same function in another function, the error below is returned when compiling.
on_function.zig:10:25: error: expected type 'u64', found 'error{Overflow,InvalidCharacter}'
const int = try std.fmt.parseInt(u64, token, 10);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
on_function.zig:3:32: note: function cannot return an error
pub fn func(input: []const u8) u64 {
^~~
referenced by:
main: on_function.zig:26:19
callMain: /<path-to-zig>/lib/std/start.zig:524:32
remaining reference traces hidden; use '-freference-trace' to see all reference traces
Below are the codes for comparison. Just compile directly with zig build-exe <file>.zig
On the main
const std = @import("std");
pub fn main() !void {
const input =
\\1 2 3
\\4 5 6
\\7 8 9
;
std.debug.print("Input: \n{s}\n", .{input});
std.debug.print("Input type: {}\n", .{@TypeOf(input)});
var lines = std.mem.tokenizeScalar(u8, input, '\n');
var total: u64 = 0;
while (lines.next()) |line| {
var tokens = std.mem.tokenizeScalar(u8, line, ' ');
while (tokens.next()) |token| {
const int = try std.fmt.parseInt(u64, token, 10);
total += int;
}
}
std.debug.print("Total: {}\n", .{total});
}
On other function called by main
const std = @import("std");
pub fn func(input: []const u8) u64 {
var lines = std.mem.tokenizeScalar(u8, input, '\n');
var total: u64 = 0;
while (lines.next()) |line| {
var tokens = std.mem.tokenizeScalar(u8, line, ' ');
while (tokens.next()) |token| {
const int = try std.fmt.parseInt(u64, token, 10);
total += int;
}
}
return total;
}
pub fn main() !void {
const input =
\\1 2 3
\\4 5 6
\\7 8 9
;
std.debug.print("Input: \n{s}\n", .{input});
std.debug.print("Input type: {}\n", .{@TypeOf(input)});
const total = func(input);
std.debug.print("Total: {}\n", .{total});
}
I’m using zig 0.13.0
for compiling.
If anyone knows the solution, can you explain to me why this behavior occurs?
PS: this is not the actual code used, I just extracted the problem into a simpler code.
Tks