Switch on @TypeOf anytype argument

Hi, this function fails with the error error: operand of switch loop has comptime-only type 'lang.Type':

fn msgLen(msg: anytype) u16 {                                                   
    const T = @TypeOf(msg);                                                     
                                                                                
    var size: usize = 0;                                                        
                                                                                
    sw: switch (@typeInfo(T)) {                                                 
        .@"struct" => |info| for (info.field_types, info.field_names) |ty, name| {
            switch (ty) {                                                       
                i32, u32, ObjectId => size += @sizeOf(ty),                         
                []const u8 => size += @sizeOf(u32) + roundUp(4, @field(msg, name).len),
                else => unreachable,                                               
            }                                                                      
        },                                                                         
        .@"union" => continue :sw @field(msg, @tagName(msg)),                      
        else => unreachable,                                                       
    }                                                                              
                                                                                   
    return @intCast(size);                                                         
} 

Is there a way around this, or do I have to pass the type as an argument?

@TypeOf of an anytype is not the problem.

Without being able to test it because surrounding functions are missing, but continue :sw @field(msg, @tagName(msg)) is likely a different type than the type of @typeInfo(T)? Did you mean to continue :sw @typeInfo(@FieldType(msg, @tagName(msg))) or something like that?

Otherwise a recursive function call might be easier to understand & give better error messages right now than a switch-loop.

1 Like