const std = @import("std");
const expect = std.testing.expect;
const eq = std.testing.expectEqual;
const Point = struct { x: i32, y: i32 };
const Color = enum { red, green, blue };
const Number = union(enum) { integer: i32, fraction: f32 };
const Score = u16;
fn increment(value: i32) i32 { return value + 1; }
test "integer widths floats bool and Unicode code points" {
try eq(@as(i8, -128), std.math.minInt(i8));
try eq(@as(u8, 255), std.math.maxInt(u8));
try eq(@as(i32, -2147483648), std.math.minInt(i32));
try eq(@as(u64, 18446744073709551615), std.math.maxInt(u64));
try expect(@bitSizeOf(u3) == 3 and @bitSizeOf(u128) == 128);
const pi: f32 = 3.14;
const e: f64 = 2.71828;
try expect(pi > 3 and e < 3);
try expect(@bitSizeOf(f16) == 16 and @bitSizeOf(f80) == 80 and @bitSizeOf(f128) == 128);
try expect(true and !false);
const ascii: u8 = 'A';
const han: u21 = '天';
try eq(@as(u8, 65), ascii);
try expect(han > 255 and "天".len == 3);
}
test "array slice vector tuple alias optional and pointer" {
var a = [_]i32{ 1, 2, 3, 4, 5 };
const s: []i32 = a[1..4];
try eq(@as(usize, 3), s.len);
s[0] = 9;
try eq(@as(i32, 9), a[1]);
const vector: @Vector(4, i32) = .{ 1, 2, 3, 4 };
try eq(@as(i32, 10), @reduce(.Add, vector));
const tuple = .{ @as(u8, 3), true };
try expect(tuple[0] == 3 and tuple[1]);
const score: Score = 42;
try eq(@as(u16, 42), score);
const optional: ?u8 = null;
try eq(@as(u8, 7), optional orelse 7);
var value: i32 = 10;
const pointer: *i32 = &value;
pointer.* = 12;
const readonly: *const i32 = pointer;
try eq(@as(i32, 12), readonly.*);
const function: *const fn (i32) i32 = &increment;
try eq(@as(i32, 6), function(5));
}
test "struct enum and tagged union payloads" {
const p = Point{ .x = 10, .y = 20 };
try eq(@as(i32, 30), p.x + p.y);
try expect(Color.green != Color.red);
const n = Number{ .integer = 10 };
const value = switch (n) { .integer => |v| v, .fraction => |v| @as(i32, @intFromFloat(v)) };
try eq(@as(i32, 10), value);
}
本例需在 Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验
入口文件:projects/zig-lab/zig-datatype.zig
预期结果与验证条件观察提示
- 该文件全部具名测试真实通过,未跳过或把编译成功当成执行完成。
- 具体输入、分支及数值由本章源码的expect/eq/expectError逐项核对;源码哈希与运行记录对应。
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联14章) · 含当前章节或实例 · mbskycom202611a544.zip