Определение struct
Объединяйте поля в один тип.
«Определение struct» — бесплатный урок Mojo Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Mojo Academy, подпишись на CoddyKit PRO. Курс Mojo Academy содержит 4 уроков всего.
Чему я научусь в уроке «Определение struct»?
Объединяйте поля в один тип. Ты практикуешь Mojo Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Mojo Academy?
Предыдущий опыт не требуется. Mojo Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Определение struct»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Mojo Academy?
Да. Каждый урок Mojo Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Определение struct
- Поля и метод __init__
- Добавление методов в struct
- Struct и классы Python