Ability key
We already covered two out of four abilities: Drop and Copy. They affect the behavior of a value in a scope and are not directly related to storage. Now it is time to cover the key ability, which allows a struct to be stored.
Defining an Object
For a struct to be considered an object and used with storage functions, it must fulfill three strict requirements:
- The
keyAbility: The struct must be declared withhas key. - The
idField: The very first field in the struct must be namedidand have the typeUIDorNamedId. - The
storeRequirement: All other fields within the struct must have thestoreability.
/// `User` object definition.
public struct User has key {
id: UID,
name: String, // field types must have `store`
}
/// Creates a new instance of the `User` type.
/// Uses the special struct `TxContext` to derive a Unique ID (UID).
public fun new(name: String, ctx: &mut TxContext): User {
User {
id: object::new(ctx), // creates a new UID
name,
}
}
Note
UIDis a type that does not have thedroporcopyabilities. Because every object contains aUID, objects themselved can never be dropped or copied. This ensures that assets cannot be accidentally deleted or duplicated, enforcing strict scarcity and accountability.
Types with the key Ability
Due to the UID or NamedId requirement for types with key, none of the native types in Move can have the key ability, nor can any of the types in the Standard Library. The key ability is present only in some Stylus Framework types and in custom types.
Summary
- The
keyability defines an object - The first field of an object must be id with type
UID - Fields of a
keytype must the havestoreability - Objects cannot have
droporcopy
The key ability defines objects in Move and forces the fields to have store. In the next section we cover the store ability to later explain how storage operations work.