Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generation of types in zig (zig language)

Tags:

zig

Is it possible to create a comptime function in zig that would generate a new struct type? The function would receive an array of strings and an array of types. The strings are the names of subsequent struct fields.

like image 702
az5112 Avatar asked Apr 27 '20 19:04

az5112


People also ask

Does Zig have reflection?

Zig is an imperative, general-purpose, statically typed, compiled system programming language designed by Andrew Kelley. The language is designed for "robustness, optimality and maintainability", supporting compile-time generics, reflection and evaluation, cross-compilation and manual memory management.

What is Zig Comptime?

In Zig, the programmer can label variables as comptime. This guarantees to the compiler that every load and store of the variable is performed at compile-time. Any violation of this results in a compile error.

Should I learn Zig or rust?

Zig is faster to type and faster to say than Rust. Though way behind "C", Rust comes out way ahead of Zig, alphabetically. Both are based on LLVM and low-level enough that the user can control almost everything given to LLVM. In this way their best-case run-time performance is pretty much identical.

How do I add a Zig to my path?

This is the most straight-forward way of obtaining Zig: grab a Zig bundle for your platform from the Downloads page, extract it in a directory and add it to your PATH to be able to call zig from any location.


1 Answers

This has been implemented now as https://github.com/ziglang/zig/pull/6099

const builtin = @import("std").builtin;
const A = @Type(.{
    .Struct = .{
        .layout = .Auto,
        .fields = &[_]builtin.TypeInfo.StructField{
            .{ .name = "one", .field_type = i32, .default_value = null, .is_comptime = false, .alignment = 0 },
        },
        .decls = &[_]builtin.TypeInfo.Declaration{},
        .is_tuple = false,
    },
});
test "" {
    const a: A = .{ .one = 25 };
}

The TypeInfo struct is defined here.

like image 85
pfg Avatar answered Nov 10 '22 22:11

pfg