Bag Module
Theiota::bag module provides a heterogeneous map-like collection that can store values of different types. Unlike Table, a Bag doesn’t constrain all values to a single type.
Source: crates/iota-framework/packages/iota-framework/sources/bag.move
Core Type
Bag
- Can store values of different types
- Keys must have
copy + drop + storeabilities - Values must have
storeability - Has
key + storeabilities itself - Prevents accidentally stranding field values
Creating Bags
new
Create a new empty bag:Transaction context
Bag Operations
add
Add a key-value pair to the bag:Mutable reference to the bag
Key to add (must have copy + drop + store)
Value to add (must have store)
EFieldAlreadyExists if the key already exists.
Example:
borrow
Immutably borrow a value from the bag:Reference to the bag
Key to look up
EFieldDoesNotExistif the key doesn’t existEFieldTypeMismatchif the value has a different type
borrow_mut
Mutably borrow a value from the bag:Mutable reference to the bag
Key to look up
remove
Remove a key-value pair and return the value:Mutable reference to the bag
Key to remove
contains
Check if a key exists (without specifying value type):Reference to the bag
Key to check
contains_with_type
Check if a key exists with a specific value type:Reference to the bag
Key to check
length
Get the number of entries in the bag:Reference to the bag
is_empty
Check if the bag is empty:Reference to the bag
Destroying Bags
destroy_empty
Destroy an empty bag:Bag to destroy (must be empty)
EBagNotEmpty if the bag still contains entries.
Example:
Complete Example: Game Inventory System
Error Codes
dynamic_field:
EFieldAlreadyExists- Key already exists in the bagEFieldDoesNotExist- Key not found in the bagEFieldTypeMismatch- Value type doesn’t match
Bag Identity
LikeTable, each Bag has a unique identity:
Best Practices
- Always specify types when accessing: Bag requires explicit type parameters
- Use
contains_with_typefor type safety: Check both existence and type
- Document expected types: Comment what types are stored at each key
-
Clean up before destroying: Remove all entries before
destroy_empty - Use constants for keys: Define key constants to avoid typos
Comparison with Table
| Feature | Bag | Table |
|---|---|---|
| Value types | Heterogeneous | Homogeneous |
| Type safety | Runtime | Compile-time |
| Flexibility | High | Lower |
| Use case | Mixed item types | Single item type |
| Type specification | Required on access | Inferred from struct |