Motoko is a powerful programming language built specifically for the Internet Computer (ICP), and it comes with a great type system to help you write safe and efficient code.
Why Are Types Important in Motoko?
In programming, types are like labels for the kind of data you're working with. For example, you might have a label for a number or a string of text. In Motoko, types help ensure that your code behaves as expected and catches potential errors early. They give you safety by preventing you from doing things like adding a number to a string or calling a function with the wrong type of data.
So, if you're building a smart contract on the Internet Computer, using the right types will help keep your code secure and your app running smoothly.
Let’s go through the main types you’ll use in Motoko.
Basic Types in Motoko
Bool (True or False)
The
Bool
type represents true or false values. It’s useful when you want to make decisions in your code.
var isActive: Bool = true;
Nat (Natural Numbers)
The
Nat
type is for non-negative numbers (0 and up). It's great for counting things like how many users have signed up for your app.
var usersCount: Nat = 150;
Int (Integers)
The
Int
type represents both positive and negative numbers. It’s perfect for things like balances, where you need to track both positive and negative values.
var balance: Int = -50; // A negative balance, maybe for debt
Float (Decimal Numbers)
The
Float
type is used for numbers that require decimal points, like prices or temperatures.
var price: Float = 19.99;
Text (Strings)
The
Text
type is used for strings of characters, like names, messages, or any text.
var greeting: Text = "Hello, World!";
Null (No Value)
Null
is used to represent the absence of a value. It’s like saying “I don’t have any data for this yet.”
var notSetYet: Null = null;
Principal (Identity)
Principal
is a special type that represents identities on the Internet Computer, like users or canisters (smart contracts). Every user and canister has a unique principal.
var userId: Principal = Principal.fromText("aaaaa-aa");
Complex Types in Motoko
Now that we’ve covered the basics, let's look at some more powerful types that allow you to store and manage more complex data.
Record (A Collection of Different Data)
A record is like a box that holds different types of data. Each piece of data inside the box is called a field.
type Person = {
name: Text;
age: Nat;
};
var user: Person = { name = "Alice"; age = 30 };
Here, Person
is a record that has a name (a string) and an age (a number).
Variant (Multiple Choices)
A variant lets you store different types of data, but only one type at a time. It’s like a box that can hold one of several types.
type Result = { #Success : Nat } | { #Error : Text };
var outcome: Result = #Success(200);
Here, Result
could either be a success (with a number) or an error (with a message).
Array (List of Same Data)
An array is a list of items that are all the same type. It’s like a shopping list of numbers or names.
var numbers: [Nat] = [1, 2, 3, 4];
Vector (Dynamic List)
A vector is like an array, but it can grow and shrink in size. It’s useful when you don’t know how many items you’ll have in advance.
import Array;
var numbers: Array.Array<Nat> = Array.make<Nat>(0);
Array.push<Nat>(numbers, 1);
Array.push<Nat>(numbers, 2);
Function Types (What the Code Does)
Motoko lets you define functions that do things like add numbers or display a message. Functions can also have types, which describe the input and output.
let add: (Nat, Nat) -> Nat = func(a, b) { a + b };
Actor Types (Smart Contracts)
In Motoko, an actor is a smart contract that holds the state and responds to requests. Every actor can have its types for state and functions.
actor Counter {
var count: Nat = 0;
public func increment() : async Nat {
count += 1;
return count;
}
}
Optional Types (Maybe We Have Data, Maybe We Don’t)
Sometimes, you don’t know if a value will exist. That’s where optional types come in. They can either hold a value or be empty.
type Option<T> = { #Some : T } | { #None : Null };
var result: Option<Nat> = #Some(42); // Has a value
Types in Motoko might seem complicated at first, but they’re a powerful tool to help you write clean, secure, and reliable code. Whether you’re dealing with simple numbers, more complex data like records and arrays, or even smart contracts (canisters), understanding how to use types will make your development process smoother and safer.
By using the right types in your smart contracts, you’re setting yourself up for success on the Internet Computer. Happy coding!