-
Notifications
You must be signed in to change notification settings - Fork 3
Type
Chung Leong edited this page Apr 24, 2024
·
2 revisions
A type in the Zig language is a special data type that refers to other data types. It's a comptime-only type.
Functions that accept type
as arguments cannot be exported by Zigar:
const std = @import("std");
pub const Uint32 = u32;
pub fn printTypeName(comptime T: type) void {
std.debug.print("{s}\n", .{@typeName(T)});
}
import { printTypeName, Uint32 } from './type-example-1.zig';
printTypeName(Uint32);
import { printTypeName, Uint32 } from './type-example-1.zig';
^^^^^^^^^^^^^
SyntaxError: The requested module './type-example-1.zig' does not provide an export named 'printTypeName'
Constants of the type type
can be exported:
pub const Int32 = i32;
pub const FatalError = error{ ate_expired_doritos, thought_cat_was_pillow };
pub const PizzaTopping = enum { pine_apple, anchovy, baked_beans, pierogi };
pub const Point = struct { x: f32, y: f32 };
import { FatalError, Int32, PizzaTopping, Point } from './type-example-2.zig';
console.log(new Int32(1234).valueOf())
console.log(new Point({ x: 0.5, y: 0.7 }).valueOf());
for (const [ name, item ] of PizzaTopping) {
console.log(`${item}`);
}
for (const [ name, error ] of FatalError) {
console.log(`${error}`);
}
1234
{ x: 0.5, y: 0.699999988079071 }
pine_apple
anchovy
baked_beans
pierogi
Error: Ate expired doritos
Error: Thought cat was pillow
Types stored in anonymous structs can also be exported:
pub const SmallIntegers = .{
.u1 = u1,
.u2 = u2,
.u3 = u3,
.u4 = u4,
.u5 = u5,
.u6 = u6,
.u7 = u7,
};
import { SmallIntegers } from './type-example-3.zig';
console.log(new SmallIntegers.u2(3).valueOf());
3
Comptime fields can be of the type type
:
fn Point(comptime T: type) {
return struct {
x: T,
y: T,
comptime Type: type = T,
};
};
pub const PointI32 = Point(i32);
pub const PointI64 = Point(i64);
pub const PointF32 = Point(f32);
pub const PointF64 = Point(f64);
import { PointI32, PointI64 } from './type-example-4.zig';
const p1 = new PointI32({ x: 45, y: -12 });
console.log(p1.Type.name, p1.valueOf());
const p2 = new PointI64({ x: 45, y: -12 });
console.log(p2.Type.name, p2.valueOf());
i32 { x: 45, y: -12, Type: {} }
i64 { x: 45n, y: -12n, Type: {} }