定义 struct
将字段组合为一种类型
定义 struct 是 CoddyKit 上的免费 Mojo Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Mojo Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Mojo Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why You Need a struct
When values belong together, like a point's x and y, you can bundle them into one custom type. In Mojo that bundle is a struct. 📦
The struct Keyword
You define a new type with the struct keyword, a name, and a colon. Everything indented under it belongs to that type.
struct Point:
passNaming Your Type
Struct names use CapitalizedNames by convention, so Point or BankAccount. This makes your types easy to spot in code.
struct BankAccount:
passFields Hold the Data
Inside a struct you list its fields, the named pieces of data it stores. Each field is declared with var and a type.
struct Point:
var x: Int
var y: IntEvery Field Needs a Type
Mojo structs are static, so each field must state its type up front. That lets the compiler lay out memory efficiently.
var name: String
var age: IntA struct Is a Blueprint
A struct definition is just a blueprint. It describes the shape of data but does not create any actual value on its own yet.
Instances Are the Real Thing
From one blueprint you make many instances, each with its own values. The struct is the mold; instances are what comes out of it.
Grouping Beats Loose Variables
Without a struct you juggle separate x and y variables everywhere. A struct keeps related data together, so it travels as one unit.
Structs Are Value Types
In Mojo a struct is a value type. Assigning it copies the data, which keeps behavior predictable and fast by default.
A Complete Mini Struct
Here is a full struct with two fields. This single definition now describes every Point your program will ever create.
struct Point:
var x: Int
var y: IntRead It Top to Bottom
Read a struct as: here is a new type, and here is the data it carries. That mental model carries you through the whole course.
Quick Check
Let us check your grasp of defining a struct.
Recap
You met the struct: a blueprint that bundles typed fields into one value type. Next you will fill it with real data using __init__. 🎉
常见问题解答
「定义 struct」课时是免费的吗?
是的 — 「定义 struct」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Mojo Academy 课程的其余内容,请升级到 CoddyKit PRO。 Mojo Academy 课程共包含 4 节课。
「定义 struct」这节课中我会学到什么?
将字段组合为一种类型 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Mojo Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Mojo Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「定义 struct」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Mojo Academy 课中编写并运行代码吗?
能。每节 Mojo Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。