genericsstructzig

How to do generics in a struct field in zig


I'm very new to zig and I'm wondering how to create a struct field that can have a compile time known type

for example something similar to the comptime keyword when used with a function parameter, I want to do the same thing to a struct field that is an array

example of comptime in function:

fn exampleFn(comptime t: type, allocator: std.mem.Allocator) ![]t {
    var array: []t = try allocator.alloc(t, 3);
    return array;
}

here I can specify any type to be the type of the output array (this is the best example I could come up with)

example of what I want to be able to do:

const List = struct {
    content_type: type,
    data: ?[].content_type,
};

is there any way I could do something like this and still be able to use the struct in runtime?


Solution

  • Zig does generics by having functions that return types.

    const std = @import("std");
    
    fn Foo(comptime value_type: type) type {
        return struct {
            value: value_type,
        };
    }
    
    const FooU8 = Foo(u8);
    
    pub fn main() void {
        var foo = FooU8{
            .value = 1,
        };
        // foo.value = 257; // error: type 'u8' cannot represent integer value '257'
        std.log.info("{}", .{ foo.value });
    }