6

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?

1 Answer 1

7

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 });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.