定长整数:i32、u8、usize
选择所需的确切位宽。
定长整数:i32、u8、usize 是 CoddyKit 上的免费 Zig Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Zig Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Zig Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Integers Carry Their Size
In Zig the width of an integer is part of its type. You always know exactly how many bits a number uses. 🔢
Signed Integers Start with i
A type like i32 is a signed 32-bit integer. The i means it can hold negative values as well as positive ones.
const temperature: i32 = -15;Unsigned Integers Start with u
An u8 is an unsigned 8-bit integer. With no sign bit it stores only non-negative values, from 0 up to 255.
const level: u8 = 200;Pick the Width You Need
The number after i or u is the bit width. A u8 covers 0 to 255, while a u16 reaches all the way up to 65535.
usize for Sizes and Indexes
The usize type is an unsigned integer sized to hold any memory address or index on your machine. Use it for lengths.
const count: usize = 42;isize Is Its Signed Cousin
The isize type matches usize in width but is signed. Reach for it when an index-sized value can also go negative.
Why Explicit Sizes Help
Fixed widths make memory and overflow predictable. You never have to guess how big an int is on a given platform.
Annotate or Let Zig Infer
You can label a value with a type, or let Zig infer it from context. A bare literal often becomes a comptime integer.
const x: i32 = 100;
const y = 7;Values Must Fit the Type
Zig refuses to store a value that does not fit. Assigning 300 to a u8 is a compile error, since u8 stops at 255.
Convert Widths with @intCast
To move between integer widths you ask explicitly. The @intCast built-in converts a value to a different integer type.
const big: u32 = 250;
const small: u8 = @intCast(big);Read the Range in the Name
The name tells you everything: i8 ranges from -128 to 127, while u16 spans 0 to 65535. The width and sign are right there.
Quick Check
You need a value that stores the length of an array or a memory index. Which integer type is the natural fit?
Recap
Zig integers name their sign and width: i32, u8, and usize. Pick the smallest type that fits, and cast on purpose when widths differ. 🎯
常见问题解答
「定长整数:i32、u8、usize」课时是免费的吗?
是的 — 「定长整数:i32、u8、usize」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Zig Academy 课程的其余内容,请升级到 CoddyKit PRO。 Zig Academy 课程共包含 4 节课。
「定长整数:i32、u8、usize」这节课中我会学到什么?
选择所需的确切位宽。 你通过在浏览器中直接运行的动手代码来练习 Zig Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Zig Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Zig Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「定长整数:i32、u8、usize」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Zig Academy 课中编写并运行代码吗?
能。每节 Zig Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 定长整数:i32、u8、usize
- 浮点数:f32 与 f64
- bool、void 与 comptime 类型
- 数字字面量与下划线