Rogue has unique type system which is very flexible and customizable. Each type can have up to 4 abilities which define how values of this type can be used, dropped or stored.
There are 4 type abilities: Copy, Drop, Store and Key.
- Copy - value can be copied (or cloned by value).
- Drop - value can be dropped by the end of scope.
- Key - value can be used as a key for global storage operations.
- Store - value can be stored inside global storage.
On this page we will go through
Drop abilities in detail; more context over
Store abilities will be given when we get to Resources chapter.
Primitive and built-in types' abilities are pre-defined and unchangeable: integers, vector, addresses and boolean values have copy, drop and store abilities
However when defining structs you can specify any set of abilities using this syntax:
Or by example:
Before we jump into how to use abilities and what they bring into the language, let's see what happens if there's a type with no abilities.
If you try to run this code, you'll get the following error:
Country::new_country() creates a value; this value is not passed anywhere and automatically dropped when function ends; but Country type doesn't have Drop ability, and it fails. Now let's change our struct definition and add Drop Ability.
Using abilities syntax we add
has drop specifying
drop ability for this struct. All of the instances of this struct will have drop ability and hence will be droppable.
Now, when struct
Country can be dropped, our script can be run.
Note: Drop ability only defines drop behavior. Destructuring does not require Drop.
We learned how to create new instances of struct
Country and drop them. But what if we wanted to create a copy? By default, structs are passed by value; and to create a copy of this struct we will use keyword
copy (you will learn more about this behavior in the next chapter):
As you could expect, making a copy of type without copy ability failed. Compiler message is clear:
With that change code above would compile and run.
- Primitive types have store, copy and drop.
- By default structs have no abilities.
- Copy and Drop abilities define whether value can be copied and dropped respectively.
- It is possible to set up to 4 abilities for a struct.