0Pricing
Zig Academy · 课时

声明结构体与字段

将相关数据组合成一种类型。

声明结构体与字段 是 CoddyKit 上的免费 Zig Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Zig Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Zig Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Group Related Data

Loose variables get messy fast. A struct lets you bundle related values into one named type you can pass around together.

struct Is an Expression

In Zig a struct is created with the struct keyword and a body. You usually bind it to a const to give the type a name.

const Point = struct {};

Add Some Fields

Inside the braces you list fields, each with a name and a type. These describe the data every value of the struct holds.

const Point = struct {
    x: i32,
    y: i32,
};

Fields End With a Comma

Every field declaration ends with a comma, even the last one. Zig is strict here, so the formatter keeps it consistent.

const Color = struct {
    r: u8,
    g: u8,
    b: u8,
};

Make an Instance

To create a value you write the type name and a .{} initializer, setting each field by name.

const origin = Point{ .x = 0, .y = 0 };

Dot to Read a Field

Reach a field with a dot after the value. So origin.x reads the x field of that point.

const px = origin.x;

Mutating Needs var

To change a field, the instance must be a var. A const struct, and all its fields, stay immutable.

var p = Point{ .x = 1, .y = 2 };
p.x = 5;

Fields Can Be Any Type

A field can hold anything: a bool, a slice, even another struct. Structs nest freely to model richer shapes.

const Line = struct {
    start: Point,
    end: Point,
};

Order of Fields

In an ordinary struct Zig may reorder fields in memory for packing. You name fields, so layout never affects your code.

Structs Are Value Types

Assigning or passing a struct copies it by value. The original is untouched unless you deliberately use a pointer.

var a = Point{ .x = 1, .y = 1 };
var b = a; // b is a copy

A Type, Not a Variable

A struct definition describes a type, like a blueprint. Instances are the actual values you build from that blueprint.

Quick Check

How do you build a value from a struct type?

Recap

You met structs: the struct keyword groups named fields into a type, and Type{ .field = value } builds an instance. 🧱

常见问题解答

「声明结构体与字段」课时是免费的吗?

是的 — 「声明结构体与字段」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Zig Academy 课程的其余内容,请升级到 CoddyKit PRO。 Zig Academy 课程共包含 4 节课。

「声明结构体与字段」这节课中我会学到什么?

将相关数据组合成一种类型。 你通过在浏览器中直接运行的动手代码来练习 Zig Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Zig Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Zig Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「声明结构体与字段」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Zig Academy 课中编写并运行代码吗?

能。每节 Zig Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 声明结构体与字段
  2. 方法与 self 参数
  3. 字段默认值
  4. 匿名结构体与元组
← 返回 Zig Academy