const std = @import("std");
const expect = std.testing.expect;
const eq = std.testing.expectEqual;
fn runtimeValue(x: i32) i32 { return x * 2; }
const global_limit: usize = 8;
test "mutable values runtime const and typed conversion" {
var count: i32 = 20;
count = 40;
const immutable = runtimeValue(count);
var entropy: [1]u8 = undefined;
std.crypto.random.bytes(&entropy);
const runtime_bound = runtimeValue(@as(i32, entropy[0]));
try eq(@as(i32, entropy[0]) * 2, runtime_bound);
try eq(@as(i32, 80), immutable);
const float: f64 = @floatFromInt(@as(i32, 120));
try eq(@as(f64, 120), float);
const back: i16 = @intCast(count);
try eq(@as(i16, 40), back);
var initialized_later: i32 = undefined;
initialized_later = 7;
try eq(@as(i32, 7), initialized_later);
}
test "comptime expression block and pointer constness" {
const size = comptime 2 * 5;
var array: [size]u8 = undefined;
@memset(&array, 0);
try eq(@as(usize, 10), array.len);
comptime { if (global_limit != 8) @compileError("wrong global limit"); }
var mutable: i32 = 5;
const pointer: *i32 = &mutable;
pointer.* = 6;
try eq(@as(i32, 6), mutable);
{ const block_value: u8 = 3; try eq(@as(u8, 3), block_value); }
}
本例需在 Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验
入口文件:projects/zig-lab/zig-var-const.zig
预期结果与验证条件观察提示
- 该文件全部具名测试真实通过,未跳过或把编译成功当成执行完成。
- 具体输入、分支及数值由本章源码的expect/eq/expectError逐项核对;源码哈希与运行记录对应。
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联14章) · 含当前章节或实例 · mbskycom202611a544.zip