#is dynamic struct field assignment possible/idiomatic?

1 messages · Page 1 of 1 (latest)

tawny tartan
#

Im using SQLite to store data for a Zig application. I'm trying to implement a ORM of sorts that takes a comptime T: type field that gets populated dynamically by the query:

pub fn run(query: *@This(), comptime T: type) ![]T {
  var result = std.ArrayList(T).init(query.allocator);
  errdefer result.deinit();
  while(sqlite3_step(query.stmt)) == .row) {
    const column_count = sqlite3.data_count(query.stmt);
    if(column_count < 0) @panic("invalid column count");

    var i: c_int = 0;
    while(i < column_count):(i+=1) {
      var column_name = sqlite3.column_name(query.stmt, i);
        inline for (std.meta.fields(T)) |f| {
        if(std.mem.eql(u8, std.mem.span(column_name), f.name)) {
          std.log.info("matching column: {s} {any}", .{f.name, column_type});
          // how to assign result here?
        }
      }
  }
}

i'm hoping that insidde that inline for... section, i can assign result.FIELD_NAME. Is this possible?

half spindle
#

Yup, you just create a var val: T = undefined; before the inline for then do @field(val, f.name) = whatever; in the loop

#

Builtins like @field don't have to follow the "normal" rules of functions, they're allowed to do stuff like return lvalues (which is what's happening here)

tawny tartan
#

oh i totally missed the @field builtin. thanks