Last active
December 25, 2024 22:13
-
-
Save zigster64/2acedc56411c0aae320b94c6c6143091 to your computer and use it in GitHub Desktop.
Parse a line of csv data into a struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn parseCSV(line: []const u8, T: type) !T { | |
var value: T = undefined; | |
var csv_fields = std.mem.splitAny(u8, line, ","); | |
inline for (std.meta.fields(T)) |field| { | |
const csv_string = csv_fields.next() orelse ""; | |
switch (field.type) { | |
i32 => @field(value, field.name) = try std.fmt.parseInt(i32, csv_string, 10), | |
f64 => @field(value, field.name) = try std.fmt.parseFloat(f64, csv_string), | |
[]const u8 => @field(value, field.name) = csv_string, | |
else => {}, | |
} | |
} | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment