beginner
+200 XP

Structs & Custom Types

Create your own data types with structs and understand abilities - the foundation of digital assets

Lesson Syllabus

Struct Basics
📦

What Are Structs?

Structs are custom data types that group related values together. Like a container holding different pieces of information. Think of it like creating your own type!

✏️

Defining Your First Struct

Syntax: public struct Name has abilities { field: type, ... }. The 'public' keyword makes it accessible from other modules. Abilities (we'll learn these next!) control what you can do with the struct.

🏗️

Creating Struct Instances

After defining a struct, create instances (actual values) using struct_name { field: value, ... }. All fields must be provided!

🎯

Accessing Fields

Use dot notation (struct.field) to read or modify fields. You need a mutable reference (&mut) to modify fields.

Abilities - Move's Superpowers
🦸

What Are Abilities?

Abilities are permissions that control what operations are allowed on a type. They're Move's way of enforcing safety rules. Think of them as superpowers you grant to your struct!

🔑

The 'key' Ability

The 'key' ability allows a struct to be stored as a top-level object. In Sui, this is what turns a struct into a Sui Object - something that can be owned by an address and transferred!

📥

The 'store' Ability

The 'store' ability allows a struct to be stored inside OTHER structs. Assets need 'store' to be held in wallets or other containers.

📋

The 'copy' Ability

The 'copy' ability allows a struct to be copied (duplicated). NEVER use this for digital assets like money or NFTs - you'd be able to duplicate value!

🗑️

The 'drop' Ability

The 'drop' ability allows a struct to be discarded/destroyed without explicit handling. Assets should NOT have 'drop' - you'd be able to accidentally destroy value!

🎯

Choosing Abilities Wisely

Rule of thumb: Regular data gets copy+drop. Digital assets get key+store (NO copy/drop). Choose abilities based on what the struct represents!

Working with Structs
📦➡️

Destructuring Structs

Destructuring unpacks all fields from a struct at once. Useful when you need multiple fields or want to consume the struct.

✏️

Updating Struct Fields

To modify struct fields, you need a mutable reference (&mut). This ensures ownership rules are followed and prevents accidental modifications.

🏗️

Constructor Pattern

Common pattern: create a constructor function that returns initialized struct instances. This encapsulates creation logic and ensures valid initial state.